C ++ partial specialization: how can I highlight this template <class T1, class T2> into this template <class T1>?
#include <iostream>
using namespace std;
template <class T1, class T2>
class A {
public:
void taunt() { cout << "A"; }
};
template <class T1>
class A<T1, T1> {
public:
void taunt() { cout << "B"; }
};
class B {};
class C {};
int main (int argc, char * const argv[]) {
A<B> a;
return 0;
}
How can I convert my two parameter templates to a single parameter template?
The above code will give a compiler error in 'A a;' for "wrong number of template arguments".
+3
2 answers
Template specialization cannot be used to reduce the number of template arguments, for this you must use the default values for some arguments.
So, to allow the use of only one argument and make this use successful in your area of expertise, you need a second argument by default, which matches the first argument:
#include <iostream>
using namespace std;
template <class T1, class T2=T1>
class A {
public:
void taunt() { cout << "A"; }
};
template <class T1>
class A<T1, T1> {
public:
void taunt() { cout << "B"; }
};
class B {};
class C {};
int main (int argc, char * const argv[]) {
A<B> a;
a.taunt(); // Prints "B"
return 0;
}
+6