升压MPL:呼叫(成员)只有当它存在 [英] Boost MPL: Call a (member) function only if it exists

查看:169
本文介绍了升压MPL:呼叫(成员)只有当它存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了一个模板参数T.有其中T类提供了一个功能func1的(),并有使用案例,其中T没有提供它的用例A级。
函数f()是在应该调用func1的(),当且仅当它的存在。我想这应该是可能的升压MPL,但我不知道怎么办。
这里是一些伪code:

 模板<类T>
A级
{
    无效F(T参数)
    {
        如果(T :: func1的是现有功能)
            param.func1();
    }
};

更妙的是别的情况:

 模板<类T>
A级
{
    无效F(T参数)
    {
        如果(T :: func1的是现有功能)
            param.func1();
        其他
            COUT<< func1的不存在&所述;&下; ENDL;
    }
};


解决方案

Boost.MPL不与处理,因为它是严格用于TMP,你不能调用成员TMP。 Boost.Fusion和Boost.TypeTraits没有任何事;我想他们中的一个会,但显然我记错。

<一个href=\"http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence/264088#264088\">Here和<一个href=\"http://stackoverflow.com/questions/1005476/how-to-detect-whether-there-is-a-specific-member-variable-in-class\">here是关于如何写一个特征来检测在C ++ 03的成员一些解决方案。一旦你有这样的特质(我称之为 has_​​func1_member ),你可以用它来SFINAE:

 模板&LT; typename的T&GT;
TYPENAME的boost :: enable_if&LT; has_​​func1_member&LT; T&GT; &GT; ::类型
maybe_call(T&amp; T公司)
{t.func1(); }模板&LT; typename的T&GT;
类型名的boost :: disable_if&LT; has_​​func1_member&LT; T&GT; &GT; ::类型
maybe_call(T&安培;)
{
    //处理缺失构件外壳
}//你的榜样code会然后做:
maybe_call(参数);

请注意,与C ++ 11它更容易编写摆在首位的特点,虽然它还是有点神秘。

I have a class A that has a template parameter T. There are use cases where the class T offers a function func1() and there are use cases where T doesn't offer it. A function f() in A should call func1(), iff it exists. I think this should be possible with boost mpl, but I don't know how. Here some pseudo code:

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

Even better would be an 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;
    }
};

解决方案

Boost.MPL doesn't deal with that as it's strictly for TMP and you can't call members in TMP. Boost.Fusion and Boost.TypeTraits don't have anything either; I thought one of them would but apparently I'm misremembering.

Here and here are some solutions on how to write a trait to detect a member in C++03. Once you have such a trait (I'll call it has_func1_member), you can use it for 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);

Note that with C++11 it's easier to write the trait in the first place, although it's still somewhat arcane.

这篇关于升压MPL:呼叫(成员)只有当它存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆