Boost MPL: call a function (member) only if it exists

I have a class A with a template parameter T. There are cases when the class T offers the function func1 (), and there are cases when T does not offer it. The function f () in should call func1 () if it exists. I think this should be possible with boost mpl, but I don't know how to do it. Here are a few pseudo codes:

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

Otherwise it would be otherwise:

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;
    }
};
+5
source share
1 answer

Boost.MPL , TMP, TMP. Boost.Fusion Boost.TypeTraits ; , , , , .

here - , ++ 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);

, ++ 11 , .

+7

All Articles