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

时间:2016-04-28 07:24:05

标签: c++ assert

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

是否可以在编译时断言,使用此特定宏的函数是特定类的成员?可以使用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);
}

2 个答案:

答案 0 :(得分:1)

您可以使用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的问题很少但是这个解决方案可能适用于很多情况。

答案 1 :(得分:1)

  

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

如果你可以使用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(
     ^