如何管理变量模板的显式特化?
我有一个标题:
// foo.h
#pragma once
template<typename T> extern T minBound;
并且在一个附近的编译单元中:
// foo.cpp
#include "foo.h"
template<> int minBound<int> = 0x80000000;
template<> short minBound<short> = 0x8000;
还有一个主要的:
// main.cpp
#include <iostream>
#include "foo.h"
int main() {
std::cout << minBound<int> << std::endl; // Hopefully -2147483648
std::cout << minBound<short> << std::endl; // Hopefully -32768
return 0;
}
编译自g++ *.cpp
.
链接器告诉我我有 multiple definition of minBound<int>
和 multiple definition of minBound<short>
.变量模板不能extern吗?我想到的是各种模板特化的不同值;我该如何着手完成这项工作?
我使用的是 Ubuntu 18.04.1,gcc 版本 7.4.0。使用 GCC 7.4 和 8.3 在 WSL 上对其进行了测试;没问题。
我知道我可以让它成为一个零参数函数,但这很无聊。
最佳答案
任何显式特化就像一个普通函数,因为它必须在使用它的任何地方声明(即,在 header 中)和在一个源文件中定义。对于变量模板,非定义声明包含 extern
,就像任何其他变量一样。但是,GCC 似乎不支持这一点(根据 Wandbox)。
关于c++ - 变量模板的显式特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154260/