开发者

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 t开发者_JAVA百科o 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);
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜