如何声明和定义具有推导类型的静态成员?

nic*_*lai 5 c++ c++17

我需要使用复杂(许多模板参数)类型定义静态成员(不是constexpr).因此,希望有这样的东西:

struct X {
    static auto x = makeObjectWithComplexType();
};
Run Code Online (Sandbox Code Playgroud)

但它不是C++.所以我试着解决它,并认为下面的代码片段可以工作,但它没有:

#include <string>

struct X {
    static auto abc() {
        return std::string();
    }

    static decltype(abc()) x;
};

decltype(abc()) X::x;

int main() {}
Run Code Online (Sandbox Code Playgroud)

它失败并出现错误:错误:在扣除'auto`之前使用'static auto X :: abc()'

有没有办法让上面的代码段工作.或者有没有其他方法来定义具有推导类型的静态成员?

gez*_*eza 3

如果你有 C++17,那么你可以这样做:

struct X {
    static inline auto x = makeObjectWithComplexType();
};
Run Code Online (Sandbox Code Playgroud)

如果你不这样做,不幸的是你必须重复makeObjectWithComplexType()

struct X {
    static decltype(makeObjectWithComplexType()) x; // declaration
};

auto X::x = makeObjectWithComplexType(); // definition
Run Code Online (Sandbox Code Playgroud)

请注意,clang 可以成功编译此版本,但 gcc 和 msvc 不能。我不确定哪个编译器是正确的,所以我在一个问题中问了它。


如果您有兴趣,为什么您的解决方法不起作用,请查看这个问题:为什么不能在类范围内推导我的类静态自动函数的类型?