【问题标题】:boost:enable_if to define a dedicated method in a templated classboost:enable_if 在模板类中定义专用方法
【发布时间】:2012-06-28 10:15:05
【问题描述】:

我想要一个自定义方法 - 我将调用 MyMethod - 在模板类中 - 我将调用 Foo - 仅当 Foo 已使用某些模板参数类型实例化时(例如,当 A 为 int 且 B 为 string 时) ,否则,我不希望 MyMethod 存在于任何其他可能的 Foo 实例上。

这可能吗?

例子:

template<class A, class B>
class Foo
{
    string MyMethod(whatever...);
}

boost:enable_if 能帮上忙吗?

谢谢!!

【问题讨论】:

标签: c++ templates boost enable-if


【解决方案1】:

您真正想要的是专门化您的模板。在你的例子中,你会写:

template<>
class Foo<int, string>
{
    string MyMethod(whatever...); 
};

你也可以使用 enable_if:

template<typename A, typename B>
class Foo
{
    typename boost::enable_if<
            boost::mpl::and_<
                boost::mpl::is_same<A, int>,
                boost::mpl::is_same<B, string>
            >,
            string>::type MyMethod(whatever...){}
};

如果没有重载,也可以使用static_assert:

template<typename A, typename B>
class Foo
{
    string MyMethod(whatever...)
    {
         static_assert(your condition here, "must validate condition");
         // method implementation follows
    }
};

当您尝试调用 MyMethod 并且条件未设置时,这将产生编译错误。

【讨论】:

  • 模板专业化有效,但我必须复制任何其他 - 标准 - Foo 方法。
  • @codeJack 然后你总是可以使用第二种方法。然而,SFINAE 对于重载解决更为重要。如果没有重载,您可以只使用 static_assert 并提供更好的错误消息。
  • 有趣,在我的例子中你会如何使用静态断言?​​
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2013-04-09
相关资源
最近更新 更多