Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "use of class template requires template argument list" mean?

Tags:

c++

templates

I am a newbie to templates so please excuse me for naive questions. I'm getting errors in this code:

template <class t>
class a{
public:
    int i;
    a(t& ii):i(ii){}
};


int main()
{
    a *a1(new a(3));
    cout<<a1.i;

    _getch();
}

Compile errors:

  1. 'a' : use of class template requires template argument list
  2. 'a' : class has no constructors
like image 446
rajya vardhan Avatar asked Jun 24 '11 19:06

rajya vardhan


2 Answers

Use

a<int> *a1(new a<int>(3));
 ^^^^^          ^^^^ 

If you want your template parameter to be automatically deduced, you can use a helper function:

template<class T>
a<T> * createA (const T& arg) //please add const to your ctor, too.
{
    return new a<T>(arg)
}
like image 105
Armen Tsirunyan Avatar answered Jan 03 '23 19:01

Armen Tsirunyan


a(t& ii):i(ii){}

This should be :

a(const t& ii):i(ii){}

So that you can pass const literals, and temporaries to the constructor.

And then do this:

a<int> *a1(new a<int>(3));

You can also write:

a<int> a2(3);
like image 28
Nawaz Avatar answered Jan 03 '23 19:01

Nawaz