2011-03-20 61 views
7

这是我如何可以有条件地使类的构造方法:有条件地允许构造

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) 
    {} 
}; 

回答

8
上的任何其他功能,但构造

可以,因为这样你可以修改函数名,包括模板参数。

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 
+0

因此,如果我理解正确,问题是要确保模板参数扣除成功。这可以通过使用类型 - foo.Method 明确地实例化模板来完成,或者使Method获取允许扣除的参数 - 模板 void方法(U * ptr,boost :: enable_if > :: type * = NULL) {} – 2011-03-20 00:22:09

+0

@MK:是的,对于大多数成员函数,您可以选择。使用构造函数,没有办法明确指定模板参数。 – 2011-03-20 00:28:03

+0

@MK:对于其他函数,'enable_if'很好地放在返回值上,以免干扰模板参数推理。唉,构造函数没有返回类型。 OTOH,没有人会接受构造函数的地址,因此没有人会为这个“隐藏的”额外论证而烦恼。 – UncleBens 2011-03-20 00:56:57

相关问题