我找到了关于如何使用类型参数(例如 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
最佳答案
关于c++ - 如何使用整数模板参数实例化模板类的静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71988315/