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

2024-04-29

我需要定义一个具有复杂(许多模板参数)类型的静态成员(不是 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 不能。我不确定哪个编译器是正确的,所以我在 a 中询问了它question https://stackoverflow.com/questions/52304410/is-it-well-formed-if-i-redefine-a-variable-as-auto-and-the-deduced-type-is-the.


如果您有兴趣,为什么您的解决方法不起作用,请查看以下问题:为什么不能在类范围内推导我的类静态自动函数的类型? https://stackoverflow.com/questions/41842987/why-cant-the-type-of-my-class-static-auto-function-be-deduced-within-the-class

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐