gpt4 book ai didi

c++ - 在模板化类中初始化静态 constexpr 成员

转载 作者:行者123 更新时间:2023-11-28 01:28:57 24 4
gpt4 key购买 nike

令我惊讶的是,我的问题还没有在这里找到答案。如果我忽略了,请随时指点我。

编辑:我收到通知说这可能是 Why can templates only be implemented in the header file? 的重复项虽然这包含很多关于编译器如何处理类模板化类的有用信息,但我仍然没有找到关于如何处理类所需的静态常量成员的信息,这些成员实际上只需要一次用于所有可能的模板实例化。

我的用例是一个模板化的 float 到字符串的转换类。一个成员函数应该是创建附加有 si 前缀的数字的函数。因此需要一些带有前缀字符的查找数组——这个数组与实际选择的模板化浮点类型无关。我做了类似的事情:

// Float2String.h
#include <string>

template <typename FloatType>
class Float2String
{

public:

//...

static std::string withSIPrefix (FloatType floatNumber, int numSignificantDigits)
{
// scale the number, convert it to a string and compute the idx to pick the right prefix...

return floatNumberScaledAndConvertedToString + siPrefixes[idx];
}

private:
static constexpr char[11][3] siPrefixes = {"f", "p", "n", "μ", "m", "", "k", "M", "G", "T", "P"};
};

// Float2String.cpp
#include "Float2String.h"

template <typename FloatType>
constexpr char Float2String<FloatType>::siPrefixes[11][3];

当尝试实际使用它时,例如转换双数,我收到以下链接器错误:

Error:Undefined symbol 'Float2String<double>::siPrefixes' referenced from:
Error: Float2String<double>::withSIPrefix(double, int) in Main.o

我在 Mac OS 上使用 Clang 并在启用 C++ 14 的情况下进行编译。

问题:我该怎么做才正确?也许可以通过不同的方法做得更好?

最佳答案

也许您可以在模板调用之外定义您的 siPrefixes。它不取决于您的模板类型。

您可以直接在您的 cpp 文件中定义它,并在您的 cpp 文件中使用 SIPrefix 实现移动方法。

关于c++ - 在模板化类中初始化静态 constexpr 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52493497/

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