【发布时间】:2019-07-22 21:57:14
【问题描述】:
如何管理变量模板的显式特化?
我有一个标题:
// 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>。变量模板不能是外部的吗?我想到的是各种模板专业化的不同值;我该怎么做呢?
我使用的是 Ubuntu 18.04.1,gcc 版本 7.4.0。使用 GCC 7.4 和 8.3 在 WSL 上对其进行了测试;没问题。
我知道,我可以让它成为一个零参数函数,但这很无聊。
【问题讨论】:
-
我认为您需要提供更多信息。您能否提供最小的
foo.h、foo.cpp和main.cpp以及您用于尝试构建程序的命令行? -
@Brian 更新。
-
无法使用 gcc 7.4.0 重现。你有什么版本?
-
g++ -c main.cpp; nm -C main.o的输出中可能有提示。 -
对未来的维护者有怜悯之心,只需将这些变量包含在一个类中(作为静态字段)。