gpt4 book ai didi

c++ - boost MPL : Call a (member) function only if it exists

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:48 27 4
gpt4 key购买 nike

我有一个类 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;
}
};

最佳答案

Boost.MPL 不处理这个问题,因为它严格针对 TMP,您不能调用 TMP 中的成员。 Boost.Fusion 和 Boost.TypeTraits 也没有任何东西;我以为其中一个会,但显然我记错了。

Herehere是关于如何在 C++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);

请注意,使用 C++11,一开始就更容易编写特征,尽管它仍然有些神秘。

关于c++ - boost MPL : Call a (member) function only if it exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7686753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com