tags:

views:

75

answers:

1

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!

+7  A: 

Since you have to name the type of a variable (C++03 can't infer the type of a variable), you can only do:

A<double> a(5.5); // that's what i don't want to 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):

template <class T>
A<T> make_a(T t) { return A<T>(t); }

and then use it like this:

another_function(make_a(1.1));

In C++0x, you will be able to do even

auto a(make_a(5.5));

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

template <>
struct A<void>
{
  A(double);
};
jpalecek
Yet another instance of 'indirection' technique
Chubsdad
thanx, i'll try to find another way
f0b0s