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:
'a' : use of class template requires template argument list
'a' : class has no constructors
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)
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With