我想要一个自定义方法 - 我将在模板类中调用 MyMethod - 我将调用 Foo - 仅当 Foo 已使用某些模板参数类型实例化时(例如,当 A 为 int 且 B 为字符串时),否则,我不希望 MyMethod 存在于任何其他可能的 Foo 实例上。
那可能吗 ?
例子:
template<class A, class B>
class Foo
{
string MyMethod(whatever...);
}
boost:enable_if 可以提供帮助吗?
谢谢!!
您真正想要的是专业化您的模板。在您的示例中,您将编写:
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 并且未设置条件时,这将产生编译错误。