How to declare and define a static member with deduced type?

自闭症网瘾萝莉.ら 提交于 2019-12-10 15:29:49

问题


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();
};

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() {}

It fails with error: error: use of ‘static auto X::abc()’ before deduction of ‘auto`*

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?


回答1:


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

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

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

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

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

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?



来源:https://stackoverflow.com/questions/51493143/how-to-declare-and-define-a-static-member-with-deduced-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!