【问题标题】:Explicit specialization of variable template变量模板的显式特化
【发布时间】: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&lt;int&gt;multiple definition of minBound&lt;short&gt;。变量模板不能是外部的吗?我想到的是各种模板专业化的不同值;我该怎么做呢?

我使用的是 Ubuntu 18.04.1,gcc 版本 7.4.0。使用 GCC 7.4 和 8.3 在 WSL 上对其进行了测试;没问题。

我知道,我可以让它成为一个零参数函数,但这很无聊。

【问题讨论】:

  • 我认为您需要提供更多信息。您能否提供最小的foo.hfoo.cppmain.cpp 以及您用于尝试构建程序的命令行?
  • @Brian 更新。
  • 无法使用 gcc 7.4.0 重现。你有什么版本?
  • g++ -c main.cpp; nm -C main.o的输出中可能有提示。
  • 对未来的维护者有怜悯之心,只需将这些变量包含在一个类中(作为静态字段)。

标签: c++ templates extern


【解决方案1】:

任何显式特化就像一个普通函数,因为它必须在任何使用它的地方声明(,在标题中)在一个源文件中定义。对于变量模板,非定义声明包含extern,就像任何其他变量一样。但是,GCC 似乎不支持这一点(每个 Wandbox)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多