如果我可以实例化某个模板类,我想使用 SFINAE 模式来执行一些代码。让我们想象一下:
//Only instantiable with types T for which T.x() is ok:
template <class T>
class TemplateClass
{
T t;
public:
void foo() {
t.x();
}
}
template <class T>
class User
{
void foo()
{
"if TemplateClass<T> is ok then do something else do nothing"
}
}
我怎么能那样做?
非常感谢!
编辑:根据 edA-qa mort-ora-y 的回答我试过:
template <class T>
struct TemplateClass
{
T t;
void foo() { t.x(); }
static const bool value = true;
};
struct A {};
struct B { void x() {} };
template <class T>
struct User
{
template<typename M>
typename boost::enable_if<TemplateClass<M> >::type func( )
{
std::cout << "enabled\n";
}
template<typename M>
typename boost::disable_if<TemplateClass<M> >::type func( )
{
std::cout << "disabled\n";
}
void foo()
{
func<TemplateClass<T> >();
}
};
User<A> a;
a.foo();
User<B> b;
b.foo();
但这会返回“启用启用”。我错过了什么?