gpt4 book ai didi

常量变量的 C++ 模板特化

转载 作者:行者123 更新时间:2023-12-02 11:51:48 26 4
gpt4 key购买 nike

我目前正在尝试拥有一个编译时常量变量,它是专门用于多种类型的模板。目前,我正在使用常量表达式,例如以下通用示例:

template<typename T>
constexpr T GENERAL_CONSTANT = T(0.01);

template<> constexpr float GENERAL_CONSTANT<float> = float(0.02);

template<> constexpr double GENERAL_CONSTANT<double> = double(0.03);

但是,此代码似乎仅适用于某些编译器/链接器。它将在适用于 Windows 10 的 Clang 9.0.0、适用于 Windows 10 的 Clang 6.0.0、适用于 Ubuntu 18.04 的 Clang 6.0.0 和适用于 Ubuntu 18.04 的 GCC 上正确编译和工作。但在其他几个配置中也给出了类似的多个重定义错误,例如 Windows 10 上的 Clang 10.0.0 或 Unix 上的 Clang 10.0.0 以及其他一些配置。错误通常类似于以下内容:

/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<double>'; <some path to a.cpp>: first defined here
/usr/bin/ld: <some path to a.cpp> multiple definition of `GENERAL_CONSTANT<float>'; <some path to a.cpp>: first defined here

其中“a.cpp”是使用常量但未定义常量的文件。因此,考虑到这个错误的发生不一致取决于编译器和机器,我很好奇这是否是解决这个问题的非标准方法,如果是这样,我应该采取什么方法?

最佳答案

变量模板的

const 限定(并且 constexpr 确实创建了一个对象 const)并不意味着内部链接, [basic.link]/p3 :

A name having namespace scope has internal linkage if it is the name of

  • a variable, variable template, function, or function template that is explicitly declared static; or

  • a non-template variable of non-volatile const-qualified type, unless [...]

这似乎是最近的更改( CWG 2387 ):

Notes from the December, 2018 teleconference:

CWG felt that a const type should not affect the linkage of a variable template or its instances.

这解释了您在 Clang-10 中观察到的差异。

作为解决方案,将变量模板及其特化标记为 staticinline。前者强制内部链接,而后者从一个定义规则中排除变量模板实例,允许多个定义,前提是它们位于单独的翻译单元中。

关于常量变量的 C++ 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62139692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com