繁体   English   中英

如何在编译时断言函数是特定类的成员

[英]How to assert at compile time, that a function is member of specific class

我有一个接口,其中每个函数的内容都是通过一个大宏创建的。 如果程序员正在添加一个新函数,却忘记了将该函数添加到接口类中,则会创建许多编译错误,从而分散了实际的错误。

是否可以在编译时断言使用该特定宏的函数是特定类的成员? C ++ 03或Boost功能可用。

#define MACRO_OF_THE_DOOM(...) assertion_here(); do_something();

class A {
    void functionA();
    void functionB();
};

// This is valid usage
void A::functionA() {
    MACRO_OF_THE_DOOM(1, 2, 3, 4, 5);
}

// This should give an understandable compile error, which tells
// definition should be A::functionB()
void functionB() {
    MACRO_OF_THE_DOOM(6, 7, 8);
}

您可以使用BOOST_STATIC_ASSERT

#define MACRO_OF_THE_DOOM(...)  { assertion_here(); do_something(); }

assertion_here() { BOOST_STATIC_ASSERT(false); }
class A {
    assertion_here() { // no-op }
    void functionA();
    void functionB();
};

可以使用type_traits解决此问题的注意事项很少,但是这种解决方案在许多情况下可能就足够了。

是否可以在编译时断言使用该特定宏的函数是特定类的成员?

如果您可以使用boost(我知道您不能使用c ++ 11),那么我建议使用TTI Library 以下是带有注释的示例:

http://coliru.stacked-crooked.com/a/66a5016a1d02117c

#include <iostream>

#include <boost/tti/has_member_function.hpp>
#include <boost/static_assert.hpp>

BOOST_TTI_HAS_MEMBER_FUNCTION(functionA)
BOOST_TTI_HAS_MEMBER_FUNCTION(functionB)

class A {
public: // must be public for tti
    void functionA();
    //void functionB();
};    

int main()
{   
    // prints 1
    std::cout << has_member_function_functionA<
       A, // class type to check
       void,    // function return type
       boost::mpl::vector<> >::value // parameter list
       << std::endl;

    // Below generates no compile error - prints 0
    std::cout << has_member_function_functionB<
       A, // class type to check
       void,    // function return type
       boost::mpl::vector<> >::value // parameter list
       << std::endl;

    // Below static assertion, will fail at compile time    
    BOOST_STATIC_ASSERT(
        (has_member_function_functionB<A,void,boost::mpl::vector<> >::value));

}

我已经进行了更新,使其与c ++ 03兼容,但是不幸的是,没有c ++ 11的静态断言会生成相当隐秘的消息:

main.cpp: In function 'int main()':
main.cpp:32:5: error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'
     BOOST_STATIC_ASSERT(
     ^
main.cpp:32:5: error: template argument 1 is invalid
     BOOST_STATIC_ASSERT(
     ^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM