2016-04-28 6 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 ::'の接頭辞を付けることを忘れてしまうことです。 '-Wall'を試しましたか? –

+0

@BartekBanachewicz私は静的なアサートがコンパイラの警告の前に表示されるので、この場合は '-Wall'よりも優れていると思います。理論的に静的なアサーションを行うことが可能かどうかにも興味があります。 –

+0

@BartekBanachewiczさらに、私が使用しているコンパイラには、この種の問題に対する警告がないようです。 –

答えて

1

あなたはtype_traitsを使用すると回避することができ、この周りにいくつかの注意点があります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(); 
}; 

使用することができますが、このソリューションは、多くの場合のために十分です。

1

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

ブーストは、(私はあなたが++、11 C使用することはできません理解して)あなたに利用可能であるならば、私は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(
    ^
関連する問題