我需要定义一个具有复杂(多个模板参数)类型的静态成员(而不是complex )。因此,我们希望有这样的东西:
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() {}它在错误中失败:错误:“静态自动X::abc()”的使用在扣除‘auto’*之前
有没有办法让上面的片段起作用。或者,还有其他方法来定义具有推导类型的静态成员吗?
发布于 2018-09-12 22:41:58
如果您有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没有。我不确定哪个编译器是正确的,所以我在一个question中问过它。
如果您感兴趣,为什么您的解决办法不起作用,请查看以下问题:Why can't the type of my class-static auto function be deduced within the class scope?
https://stackoverflow.com/questions/51493143
复制相似问题