![](/img/trans.png)
[英]How can I Declare/define/initialize a static member variable of template classes as static member variables of a class?
[英]How to declare and define a static member with deduced type?
我需要使用复杂(许多模板参数)类型定义静态成员(不是constexpr)。 因此,希望有这样的东西:
struct X {
static auto x = makeObjectWithComplexType();
};
但它不是C ++。 所以我试着解决它,并认为下面的代码片段可以工作,但它没有:
#include <string>
struct X {
static auto abc() {
return std::string();
}
static decltype(abc()) x;
};
decltype(abc()) X::x;
int main() {}
它失败并出现错误: 错误:在扣除'auto`之前使用'static auto X :: abc()'
有没有办法让上面的代码段工作。 或者有没有其他方法来定义具有推导类型的静态成员?
如果你有C ++ 17,那么你可以这样做:
struct X {
static inline auto x = makeObjectWithComplexType();
};
如果不这样做,那么你不得不重复makeObjectWithComplexType()
:
struct X {
static decltype(makeObjectWithComplexType()) x; // declaration
};
auto X::x = makeObjectWithComplexType(); // definition
请注意,clang成功编译了此版本,但gcc和msvc没有。 我不确定哪个编译器是正确的,所以我在一个问题中问过它。
如果您感兴趣,为什么您的解决方法不起作用,请查看以下问题: 为什么我的类静态自动函数的类型不能在类范围内推导出来?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.