问题
EXAMPLE
template< typename T >
struct A {
};
template< typename T, typename U >
struct A : A<T> {
};
int main() {
A<double> ad;
A<int, int> a;
}
COMPILE ERROR
g++ -std=c++17 -Wall -pedantic -pthread main.cpp && ./a.out main.cpp:9:8: error: redeclared with 2 template parameters struct A : A<T> { ^ main.cpp:4:8: note: previous declaration 'template<class T> struct A' used 1 template parameter struct A { ^ main.cpp: In function 'int main()': main.cpp:16:5: error: expected initializer before 'A' A<int, int> aii; ^
Differrent template names works fine:
template< typename T >
struct A {
};
template< typename T, typename U >
struct AA : A<T> {
};
int main() {
AA<int, int> aa;
}
Wanna have same template name. It should be possible with variadic templates but I don't know how.
Thanks for your attention
回答1:
You can use default parameters if you can define default:
template<typename T, typename U = /* default */>
struct A {
};
If you want to treat different amount of template parameter with different behavior, you can also use variadic templates and specialization for that:
template<typename...>
struct A;
template<typename T>
struct A<T> { // specialization for one parameter
};
template<typename T, typename U>
struct A<T, U> { // specialization for two parameter
};
int main() {
A<double> ad;
A<int, int> a;
// A<int, int, int> a; // error, undefined
}
来源:https://stackoverflow.com/questions/55658265/extend-templated-struct-with-additional-template-parameter-in-c