下面是我如何有条件地启用类的构造函数:
struct Foo
{
template<class T>
Foo( T* ptr, boost::enable_if<is_arithmetic<T> >::type* = NULL )
{}
};
我想知道为什么我需要通过虚拟参数启用。为什么我不能只写:
struct Foo
{
template<class T>
Foo( boost::enable_if<is_arithmetic<T>, T>::type* = NULL )
{}
};
最佳答案
您可以在除构造函数之外的任何其他函数上,因为这样您就可以修改函数名称,包括模板参数。
Foo foo;
foo.Method<T>();
但是,对于构造函数,构造函数名称永远不会出现在您的表达式中,因此没有地方可以显式放置模板参数。你必须从一个论证中推断出来。
Foo<T> foo; // no good, assumes the type Foo is a template, not its constructor
Foo* pfoo = new Foo<T>(); // same problem
Foo foo((T*)0); // ok, deduced
Foo* pfoo = new Foo((T*)0); // same
关于c++ - 有条件地启用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365817/