为什么这段代码不能编译?
template <class T>
class A
{
public:
A(T t) : t_(t) {}
private:
T t_;
};
int main()
{
A a(5.5);
// A<double> a(5.5); // that's what i don't want to do
}
Run Code Online (Sandbox Code Playgroud)
我希望模板参数是隐式的.
就像在这个例子中:
template<class T>
T Foo(T t) { return t; }
// usage:
Foo(5.5);
Run Code Online (Sandbox Code Playgroud)
更新:命名构造函数idiom对我来说是不可接受的.我想把这个类用于RAII.这样做的唯一方法是const A& a = A::MakeA(t),但它很难看!
由于您必须命名变量的类型(C++ 03无法推断变量的类型),您只能这样做:
A<double> a(5.5); // that's what i don't want to do
Run Code Online (Sandbox Code Playgroud)
当您不需要创建类型的变量但希望将其传递给其他函数时,情况会更容易一些.在这种情况下,您定义一个辅助"构造函数"(请参阅参考资料std::make_pair):
template <class T>
A<T> make_a(T t) { return A<T>(t); }
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
another_function(make_a(1.1));
Run Code Online (Sandbox Code Playgroud)
在C++ 0x中,您将能够做到均匀
auto a(make_a(5.5));
Run Code Online (Sandbox Code Playgroud)
定义你的变量a.
但是,A从构造函数推断出的参数通常是不可能的,因为你无法分辨哪些特化具有给定类型的转换构造函数.想象一下,有专业化
template <>
struct A<void>
{
A(double);
};
Run Code Online (Sandbox Code Playgroud)