有条件地启用构造函数

MK.*_*MK. 7 c++ conditional constructor

这是我如何有条件地启用类的构造函数:

struct Foo
{

    template<class T>
    Foo( T* ptr, boost::enable_if<is_arithmetic<T> >::type* = NULL )
    {}

};
Run Code Online (Sandbox Code Playgroud)

我想知道为什么我需要通过伪参数进行启用.为什么我不能写:

struct Foo
{
    template<class T>
    Foo( boost::enable_if<is_arithmetic<T>, T>::type* = NULL )
    {}
};
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 8

您可以在任何其他函数上使用构造函数,因为这样您就可以修改函数名称,包括模板参数.

Foo foo;
foo.Method<T>();
Run Code Online (Sandbox Code Playgroud)

但是,使用构造函数时,构造函数名称永远不会出现在表达式中,因此无法显式放置模板参数.你必须从论证中推断出它.

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
Run Code Online (Sandbox Code Playgroud)