Why doesn’t this code compile?
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
}
I want template arguments to be implicit.
Like in this example:
template<class T>
T Foo(T t) { return t; }
// usage:
Foo(5.5);
UPDATE: named-constructor idiom isn’t acceptable for me. I want to use this class for RAII.
The only way to do so is const A& a = A::MakeA(t), but it’s ugly!
Since you have to name the type of a variable (C++03 can’t infer the type of a variable), you can only do:
The situation is a little easier when you needn’t make a variable of the type, but want to pass it to some other function. In this case, you define an auxiliary “constructor function” (see
std::make_pair):and then use it like this:
In C++0x, you will be able to do even
to define your variable
a.However, inferring
A‘s argument from its constructor is generally impossible, because you can’t tell which specializations have the conversion constructor from a given type. Imagine there’s a specialization