简体   繁体   中英

C++ template arguments in constructor

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM