Boost MPL:调用(成员)函数,只有存在 [英] Boost MPL: Call a (member) function only if it exists
问题描述
我有一个类A,它有一个模板参数T.有一些用例,类T提供了一个函数func1(),有一些用例,T不提供它。
A中的函数f()应该调用func1(),iff它存在。我认为这应该是可能的提升mpl,但我不知道如何。
这里有一些伪代码:
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();
}
};
更好的是一个else- case:
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不处理,因为它严格用于TMP,您不能在TMP中调用成员。 Boost.Fusion和Boost.TypeTraits没有任何东西;我认为其中一个会显然是我错误的。
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.
这里和这里是一些解决方案,如何编写一个trait来检测C ++ 03中的成员。一旦你有这样的特质(我会称为 has_func1_member
),你可以使用它SFINAE:
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);
请注意,使用C ++ 11,首先写trait更容易,有点神秘。
Note that with C++11 it's easier to write the trait in the first place, although it's still somewhat arcane.
这篇关于Boost MPL:调用(成员)函数,只有存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!