Boost MPL:只在(成员)函数存在时调用它



我有一个类a,它有一个模板参数T。在某些用例中,类T提供函数func1(),而在某些用例中,类T不提供函数func1()。A中的函数f()应该调用func1(),如果它存在的话。我认为这应该是可能的与boost mpl,但我不知道如何。下面是一些伪代码:

template<class T>
class A
{
    void f(T param)
    {
        if(T::func1 is an existing function)
            param.func1();
    }
};

更好的是else-case:

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;
    }
};

MPL不处理这个问题,因为它严格适用于TMP,你不能在TMP中调用成员。提振。聚变和增强。typetrait也没有任何东西;我以为其中一个会,但显然我记错了。

这里和这里是关于如何在c++ 03中编写trait来检测成员的一些解决方案。一旦你有了这样一个特征(我称之为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);

请注意,在c++ 11中,首先更容易编写trait,尽管它仍然有些晦涩。

最新更新