How to specialize a c++ variadic template?
- by Serge
I'm trying to understand c++ variadic templates.
I'm not much aware of the correct language to use to explain what I'd like to achieve, so it might be simpler if I provide a bit of code which illustrate what I'd like to achieve.
#include <iostream>
#include <string>
using namespace std;
template<int ...A>
class TestTemplate1 {
public:
string getString() {
return "Normal";
}
};
template<int T, int ...A>
string TestTemplate1<2, A...>::getString() {
return "Specialized";
}
template<typename ...A>
class TestTemplate2 {
};
int main() {
TestTemplate1<1, 2, 3, 4> t1_1;
TestTemplate1<1, 2> t1_2;
TestTemplate1<> t1_3;
TestTemplate1<2> t1_4;
TestTemplate2<> t2_1;
TestTemplate2<int, double> t2_2;
cout << t1_1.getString() << endl;
cout << t1_2.getString() << endl;
cout << t1_3.getString() << endl;
cout << t1_4.getString() << endl;
}
This throws several errors.
error C2333: 'TestTemplate1<::getString' : error in function declaration; skipping function body
error C2333: 'TestTemplate1<1,2,3,4::getString' : error in function declaration; skipping function body
error C2333: 'TestTemplate1<1,2::getString' : error in function declaration; skipping function body
error C2333: 'TestTemplate1<2::getString' : error in function declaration; skipping function body
error C2977: 'TestTemplate1' : too many template arguments
error C2995: 'std::string TestTemplate1::getString(void)' : function template has already been defined
error C3860: template argument list following class template name must list parameters in the order used in template parameter list
How can I have a specialized behavior for every TestTemplate1<2, ...> instances like t1_4?