Hei*_*nzi 5 c++ boost sfinae boost-mpl template-meta-programming
我有一个类A,它有一个模板参数T.有一些用例,类T提供了一个函数func1(),并且有一些用例,其中T不提供它.A中的函数f()应该调用func1(),如果它存在的话.我认为这应该可以使用boost mpl,但我不知道如何.这里有一些伪代码:
template<class T>
class A
{
void f(T param)
{
if(T::func1 is an existing function)
param.func1();
}
};
Run Code Online (Sandbox Code Playgroud)
更好的是其他情况:
template<class T>
class A
{
void f(T param)
{
if(T::func1 is an existing function)
param.func1();
else
cout << "func1 doesn't exist" << endl;
}
};
Run Code Online (Sandbox Code Playgroud)
Boost.MPL没有处理它,因为它严格用于TMP,你不能在TMP中调用成员.Boost.Fusion和Boost.TypeTraits也没有任何东西; 我以为其中一个会,但显然我记错了.
这里和这里有一些关于如何编写特征来检测C++ 03中的成员的解决方案.一旦你有了这样的特性(我会称之为has_func1_member),你可以将它用于SFINAE:
template<typename T>
typename boost::enable_if<has_func1_member<T> >::type
maybe_call(T& t)
{ t.func1(); }
template<typename T>
typename boost::disable_if<has_func1_member<T> >::type
maybe_call(T&)
{
// handle missing member case
}
// your example code would then do:
maybe_call(param);
Run Code Online (Sandbox Code Playgroud)
请注意,使用C++ 11,首先编写特征会更容易,尽管它仍然有些神秘.