使用C ++中的附加模板参数扩展模板化结构

问题描述 投票:3回答:1

EXAMPLE

template< typename T >
struct A {

};

template< typename T, typename U >
struct A : A<T> {

};


int main() {
    A<double> ad;
    A<int, int> a;
}

编译错误

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;
     ^

不同的模板名称工作正常:

template< typename T >
struct A {

};

template< typename T, typename U >
struct AA : A<T> {

};


int main() {
    AA<int, int> aa;
}

想拥有相同的模板名称。它应该可以使用可变参数模板,但我不知道如何。 感谢您的关注

c++ templates variadic-templates
1个回答
6
投票

如果可以定义默认值,则可以使用默认参数:

template<typename T, typename U = /* default */>
struct A {

};

如果要使用不同的行为处理不同数量的模板参数,还可以使用可变参数模板和专门化:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.