提高:enable_if在一个模板类定义了一个专用的方法 [英] boost:enable_if to define a dedicated method in a templated class
问题描述
我想有一个自定义的方法 - 我会打电话的MyMethod - 在一个模板类 - 我会打电话给美孚 - 只有当富已实例化某些模板参数类型(例如,当A是int和B是字符串) ,否则,我不希望的MyMethod在所有存在于其他任何可能的Foo实例。
I would like to have a custom method - I will call MyMethod - in a templated class - I will call Foo - ONLY when Foo has been instanciated with certain template parameters types (eg. when A is int and B is string), otherwise, I don't want MyMethod to exist at all on any other possible Foo instance.
这可能吗?
例如:
template<class A, class B>
class Foo
{
string MyMethod(whatever...);
}
升压:enable_if可以帮助有
boost:enable_if can help there ?
谢谢!
推荐答案
你真的想在这里有什么专门模板。在你的榜样,你可以这样写:
What you really want here is to specialize your template. In your example, you would write:
template<>
class Foo<int, string>
{
string MyMethod(whatever...);
};
您也可以使用enable_if:
you can also use 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:
if there are no overloads, you can also use static_assert:
template<typename A, typename B>
class Foo
{
string MyMethod(whatever...)
{
static_assert(your condition here, "must validate condition");
// method implementation follows
}
};
这会产生一个编译错误,当您尝试调用的MyMethod和条件没有设置。
this will produce a compile error when you try to invoke MyMethod and the condition is not set.
这篇关于提高:enable_if在一个模板类定义了一个专用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!