Boost MPL:仅当(成员)函数存在时才调用它
我有一个类 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();
}
};
更好的是 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;
}
};
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;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Boost.MPL 不处理这个问题,因为它严格用于 TMP,并且您不能调用 TMP 中的成员。 Boost.Fusion 和 Boost.TypeTraits 也没有任何东西;我以为其中一个会,但显然我记错了。
这里< /a> 和 这里是一些关于如何编写一个特征来检测 C++03 中的成员。一旦你有了这样的特征(我将其称为
has_func1_member
),你就可以将它用于 SFINAE:请注意,使用 C++11 更容易首先编写该特征,尽管它仍然是有点神秘。
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:Note that with C++11 it's easier to write the trait in the first place, although it's still somewhat arcane.