c++ - 如何使用整数模板参数实例化模板类的静态成员?

标签 c++ templates c++14

我找到了关于如何使用类型参数(例如 https://stackoverflow.com/a/3229904/2995726)实例化 C++ 模板类的静态成员的问题的各种答案,但我无法将其应用于具有整数参数的模板类。

我试过这个,但模板参数有一个默认值的额外复杂性:

$ cat test.cc
#include <iostream>

template<unsigned int a = 33>
class A
{
public:
    static unsigned char x;

    static unsigned int f(void) { return x + a; }
};

// Instantiate template
template class A<>;

// Attempts to instantiate static member:
// unsigned char A<>::x;
// template<> unsigned char A<>::x;
// template<unsigned int> unsigned char A<>::x;

int main(void)
{
    A<>::x = 3;

    std::cout << A<>::f() << std::endl;
}

当我尝试使用 g++ 10.2 编译它时,出现链接器错误:

$ g++ -std=c++14 -o foo test.cc
/usr/bin/ld: /tmp/ccXGU1fT.o: in function `main':
test.cc:(.text+0x7): undefined reference to `A<33u>::x'
/usr/bin/ld: /tmp/ccXGU1fT.o: in function `A<33u>::f()':
test.cc:(.text._ZN1AILj33EE1fEv[_ZN1AILj33EE1fEv]+0x7): undefined reference to `A<33u>::x'
collect2: error: ld returned 1 exit status

三个注释行是尝试实例化静态成员变量。当我启用以下行时:

unsigned char A<>::x;

然后会发生这种情况:

test.cc:16:15: error: specializing member ‘A<>::x’ requires ‘template<>’ syntax
   16 | unsigned char A<>::x;
      |               ^~~~

使用这一行:

template<> unsigned char A<>::x;

再次导致链接器错误:

$ g++ -std=c++14 -o foo test.cc
/usr/bin/ld: /tmp/ccmw49ld.o: in function `main':
test.cc:(.text+0x7): undefined reference to `A<33u>::x'
/usr/bin/ld: /tmp/ccmw49ld.o: in function `A<33u>::f()':
test.cc:(.text._ZN1AILj33EE1fEv[_ZN1AILj33EE1fEv]+0x7): undefined reference to `A<33u>::x'
collect2: error: ld returned 1 exit status

最后一行:

template<unsigned int> unsigned char A<>::x;

导致此错误:

$ g++ -std=c++14 -o foo test.cc
test.cc:18:43: error: template parameters not deducible in partial specialization:
   18 | template<unsigned int> unsigned char A<>::x;
      |                                           ^
test.cc:18:43: note:         ‘<anonymous>’
test.cc:25: confused by earlier errors, bailing out

最佳答案

您需要定义当前仅声明的静态变量,而不是“实例化模板”

定义可能如下所示:

template<unsigned int a>
unsigned char A<a>::x{};

Demo

关于c++ - 如何使用整数模板参数实例化模板类的静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71988315/

相关文章:

c++ - 为什么这个数组大小的模板不起作用?

c++ - 从外部使用 "class::func()"调用非静态函数或构造函数

c++:将 24bpp 转换为 8bpp 或 1bpp 图像

c++ - 显式转换和模板化转换运算符

c++ - 模板变量的显式特化

angular - <ng-template></ng-template> 正在加载多次

c++ - 为什么在 C++14 中对数组的初始化仍然需要双括号?

具有可变模板初始化列表的多种类型的 C++ 运算符重载

c++ - 在 C++ 中转换为 double 时处理异常

c++ - STL SET 中项目的顺序因程序的不同运行而不同