2016-04-28 32 views
1

我有一个接口,其中每个函数的内容都是用一个大宏创建的。如果程序员正在添加一个新函数,并忘记将该函数添加到接口类中,它会创建很多编译错误,这会使实际错误分心。如何在编译时声明一个函数是特定类的成员

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

所以这样做的真正原因是你在实现它们的时候会忘记用'A ::'作为前缀的函数吗?你有没有尝试' - 墙'? –

+0

@BartekBanachewicz在这种情况下,我认为static assert会比'-Wall'更好,因为在编译器警告之前会显示编译错误。我也对这是否在理论上可能与静态断言有关感兴趣。 –

+0

@BartekBanachewicz此外,似乎我使用的编译器没有这种问题的警告。 –

回答

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

Would it be possible to assert at compile time, that a function that uses this particular macro is a member of specific class?

如果提供给你(我明白你不能使用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产生相当criptic消息:

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(
    ^
相关问题