Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally enabling constructor

Here is how I can conditionally enable a constructor of a class :

struct Foo
{

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

};

I would like to know why I need to do the enabling via a dummy parameter. Why can I not just write :

struct Foo
{
    template<class T>
    Foo( boost::enable_if<is_arithmetic<T>, T>::type* = NULL )
    {}
};
like image 451
MK. Avatar asked Mar 20 '11 00:03

MK.


1 Answers

You can on any other function but the constructor, because then you can modify the function name including the template arguments.

Foo foo;
foo.Method<T>();

With a constructor, though, the constructor name never appears in your expression, so there's no place to explicitly put the template parameter. You have to deduce it from an argument.

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
like image 191
Ben Voigt Avatar answered Oct 30 '22 21:10

Ben Voigt