如何声明和定义具有推断类型的静态成员? [英] How to declare and define a static member with deduced type?

查看:87
本文介绍了如何声明和定义具有推断类型的静态成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to define a static member (not constexpr) with a complex (many template parameters) type. Therefore it would be desired to have something like this:

struct X {
    static auto x = makeObjectWithComplexType();
};

但这不是C ++。因此,我尝试解决此问题,并认为下面的代码片段可以工作,但它无效:

But it is not C++. So I tried to workaround it, and thought the snippet below would work, but it does not:

#include <string>

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

    static decltype(abc()) x;
};

decltype(abc()) X::x;

int main() {}

失败并显示错误:错误:在扣除自动 *之前使用静态自动X :: abc() *

有什么方法可以使上面的代码段去工作。还是有其他方法来定义具有推断类型的静态成员?

Is there any way to make the snippet above to work. Or is there any other way to define a static member with a deduced type?

推荐答案

如果您使用的是C ++ 17,则您可以这样做:

If you have C++17, then you can do this:

struct X {
    static inline auto x = makeObjectWithComplexType();
};

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

If you don't, you unfortunately have to repeat makeObjectWithComplexType():

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

auto X::x = makeObjectWithComplexType(); // definition

请注意,clang可以成功编译该版本,但gcc和msvc不能。我不确定哪个编译器正确,所以我在

Note, that clang successfully compiles this version, but gcc and msvc don't. I'm not sure which compiler is right, so I've asked it in a question.

如果您有兴趣,为什么您的解决方法不起作用,请查看以下问题:

If you're interested, why your workaround doesn't work, check out this question: Why can't the type of my class-static auto function be deduced within the class scope?

这篇关于如何声明和定义具有推断类型的静态成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆