Template class expression parameter overloading
-
05-09-2019 - |
Question
Hey, I'm trying to figure out if it's possible to "overload" a template class deffinition with expression parameters. Kind of like the following snippet of code.
template<class T>
class Test
{
public:
T testvar;
Test()
{
testvar = 5;
cout << "Testvar: " << testvar << endl;
}
};
template<class T>
class Test<T, int num>
{
public:
T testvar;
Test()
{
testvar = 10;
cout << "Testvar: " << testvar << endl;
cout << "Param: " << num << endl;
}
};
Thanks.
Edit: For the record, i'm trying to do this with C++ if that wasn't obvious... :)
Solution
Templates allow default template parameters, which can provide something similar to what you're looking for..
template<class T, int num = -1>
class Test
{
public:
T testvar;
Test()
{
testvar = (num == -1 ? 10 : 5);
cout << "Testvar: " << testvar << endl;
if ( num != -1 )
cout << "Param: " << num << endl;
}
};
OTHER TIPS
If you want to be able to specify just one template argument for Test
, you will need to declare a default template parameter as Shmoopty suggests.
It's also possible to partially specialise for different parameter values:
// This base template will be used whenever the second parameter is
// supplied and is not -1.
template<class T, int num = -1>
class Test
{
public:
T testvar;
Test()
{
testvar = 10;
cout << "Testvar: " << testvar << endl;
cout << "Param: " << num << endl;
}
};
// This partial specialisation will be chosen
// when the second parameter is omitted (or is supplied as -1).
template<class T, int num>
class Test<T, -1>
{
public:
T testvar;
Test()
{
testvar = 5;
cout << "Testvar: " << testvar << endl;
}
};
This avoids the need for if
or switch
statements, which makes it marginally faster (no runtime testing is performed) and allows additional cases to be "grafted on" later in the form of additional partial specialisations. (Although which approach is clearer is a matter of personal taste.)