static constexpr chrono 作为结构成员
我有一个接口标头,具有像这样的结构( c ++ 11 ):
// header
struct MyStruct
{
std::chrono::milliseconds time_1{defaultTime};
std::chrono::milliseconds time_2{defaultTime};
std::chrono::milliseconds time_3{defaultTime};
// default value
static constexpr std::chrono::milliseconds defaultTime{5000};
};
// cpp
constexpr std::chrono::milliseconds MyStruct::defaultTime;
int main()
{
MyStruct ms{};
}
GCC和MSVC一切都很好,问题是在Clang 9上,我遇到了这个错误: 架构的未定义符号X86_64:“ MyStruct :: DefaultTime”:
我想避免代码重复,并保留该defaulttime {5000}
对我的库用户在标题中可见。但它也应该在Clang 9上进行编译。
另一种选择是,尽管我真的不喜欢默认是那里的第一个成员:
// header
struct MyStruct
{
// default value
const std::chrono::milliseconds defaultTime{5000};
std::chrono::milliseconds time_1{defaultTime};
std::chrono::milliseconds time_2{defaultTime};
std::chrono::milliseconds time_3{defaultTime};
}
还有其他选择吗?谢谢
I have an interface header with a struct like looks like this (C++11):
// header
struct MyStruct
{
std::chrono::milliseconds time_1{defaultTime};
std::chrono::milliseconds time_2{defaultTime};
std::chrono::milliseconds time_3{defaultTime};
// default value
static constexpr std::chrono::milliseconds defaultTime{5000};
};
// cpp
constexpr std::chrono::milliseconds MyStruct::defaultTime;
int main()
{
MyStruct ms{};
}
Everything is fine with GCC and MSVC, the problem is that on Clang 9 I get this error:Undefined symbols for architecture x86_64: "MyStruct::defaultTime":
I want to avoid code duplication and to keep that defaultTime{5000}
visible to my library users in the header. But it should compile on Clang 9 also.
An alternative would be this, although I don't really like to default to be the first member there:
// header
struct MyStruct
{
// default value
const std::chrono::milliseconds defaultTime{5000};
std::chrono::milliseconds time_1{defaultTime};
std::chrono::milliseconds time_2{defaultTime};
std::chrono::milliseconds time_3{defaultTime};
}
Any alternatives? thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在C ++ 11中,一个简单的修复是使用功能而不是直值。它不像您想要的语法那样干净,但是范围的打字常数只是最近才整理出来的事情之一。
在C ++ 11中的所有三个主要编译器上都可以正常工作:
https://gcc.godbolt.org/z/9w9wojhvh
如果您实际上不需要常量即可强烈键入,并且由于这是一个整数,使用枚举是一种经典的方法:
In C++11, an easy fix is to use a function instead of a straight value. It's not as clean as the syntax you want, but scoped typed constants are just one of those things that only got sorted out more recently.
Works fine on all three main compilers in C++11:
https://gcc.godbolt.org/z/9W9Wojhvh
If you don't actually need the constant to be strongly typed, and since this is an integer, using an enum is a classic way of tackling scoped integer constants: