c++ conditional compilation based on member presence
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Is it possible to write a C++ template to check for a function's existence?
在JavaScript等语言中,您可以检查是否存在属性
1 2 | // javascript if( object['property'] ) // do something |
在C++中,我想根据EDCOX1的类型0是否具有某个属性来编译编译条件。这有可能吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | template <typename T> class IntFoo { T container ; public: void add( int val ) { // This doesn't work, but it shows what I'm trying to do. // if the container has a .push_front method/member, use it, // otherwise, use a .push_back method. #ifdef container.push_front container.push_front( val ) ; #else container.push_back( val ) ; #endif } void print() { for( typename T::iterator iter = container.begin() ; iter != container.end() ; ++iter ) printf("%d", *iter ) ; puts(" --end" ) ; } } ; int main() { // what ends up happening is // these 2 have the same result (500, 200 --end). IntFoo< vector<int> > intfoo; intfoo.add( 500 ) ; intfoo.add( 200 ) ; intfoo.print() ; // expected that the LIST has (200, 500 --end) IntFoo< list<int> > listfoo ; listfoo.add( 500 ) ; listfoo.add( 200 ) ; // it always calls .push_back listfoo.print(); } |
下面的示例演示了一种可用于(在C++ 11中使用表达式的SIMEAE)的技术:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | typedef char no; typedef no (&yes)[2]; no detect_push_front( ... ); template < class C > auto detect_push_front( C &c ) -> typename std::conditional< false, decltype( c.push_front( std::declval< typename C::value_type >() ) ), yes >::type; template < class C > struct has_push_front : std::integral_constant< bool, sizeof( detect_push_front( std::declval< C & >() ) ) == sizeof( yes ) > {}; template < class C > void add( C &c, typename C::value_type v, std::true_type ) { c.push_front( v ); } template < class C > void add( C &c, typename C::value_type v, std::false_type ) { c.push_back( v ); } template < class C > void add( C &c, typename C::value_type v ) { add( c, v, has_push_front< C >() ); } int main() { std::vector< int > v; add( v, 0 ); add( v, 1 ); add( v, 2 ); std::copy( v.begin(), v.end(), std::ostream_iterator< int >( std::cout,"" ) ); std::cout << ' '; std::list< int > l; add( l, 0 ); add( l, 1 ); add( l, 2 ); std::copy( l.begin(), l.end(), std::ostream_iterator< int >( std::cout,"" ) ); std::cout << ' '; } |
输出:
1 2 | 0 1 2 2 1 0 |
你不能那样做,但你可以有
1 | template<T,TT> void push_there(T& c,T& i) { c.push_back(i); } |
以及对具有
据我所知,在C++中实现"条件编译"的唯一方法是使用预处理器DRCIETVE,如EDCOX1,0,EDCX1,1。我不存在任何其他技术。