相关疑难解决方法(0)

822
推荐指数
10
解决办法
35万
查看次数

非积分常数

我想要一个带有非整数常量的头文件,例如一个类.注意常数也并不需要是一个编译时间常数.

static const std::string Ten = "10";
Run Code Online (Sandbox Code Playgroud)

这编译但不可取,因为每个编译单元现在都有自己的Ten副本.

const std::string Ten = "10";
Run Code Online (Sandbox Code Playgroud)

这将编译但会因为多重定义的Ten的链接器错误而失败.

constexpr std::string Ten = "10"s;
Run Code Online (Sandbox Code Playgroud)

这可以工作,但前提是字符串构造函数也是constexpr.它会但是我不能指望每个非整数常量都有一个constexpr构造函数......或者我可以吗?

extern const std::string Ten = "10";
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但我担心如果我错误地呼吸,我会收到链接器错误.

inline const std::string Ten( ) { return "10"; }
Run Code Online (Sandbox Code Playgroud)

这有我想要的一切,除了干净的语法.另外,现在我必须将常量称为函数调用Ten().

inline const std::string = "10";
Run Code Online (Sandbox Code Playgroud)

这似乎是理想的解决方案.当然inline,标准不允许变量.

  • c ++标准中是否有一些内容表明外部版本应该有用,或者我很幸运它与GCC一起使用?
  • 是否有令人信服的理由不允许内联变量?
  • c ++ 03有更好的方法还是c ++ 0x会有更好的方法?

c++ inline constants c++11

16
推荐指数
3
解决办法
3971
查看次数

标签 统计

c ×1

c++ ×1

c++-faq ×1

c++11 ×1

constants ×1

declaration ×1

definition ×1

inline ×1

terminology ×1