Extend templated struct with additional template parameter in C++

谁说我不能喝 提交于 2020-01-14 19:42:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!