可能重复:
是否可以编写 C++ 模板来检查函数是否存在?
在 JavaScript 等语言中,您可以检查属性是否存在
// javascript
if( object['property'] ) // do something
在 C++ 中,我想根据类型T
是否具有特定属性来条件编译。这可能吗?
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( "\n--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();
}