【发布时间】:2012-09-25 15:22:06
【问题描述】:
可能重复:
Is it possible to write a C++ template to check for a function's existence?
在 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();
}
【问题讨论】:
-
哇! “替换失败不是错误”(SFINAE)!
-
您可以编写一个特征来检查成员函数的存在(至少在 C++11 中)。 pretty printer 代码包含
begin()成员函数的特征示例。