Reputation: 1222
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?
Upvotes: 5
Views: 202
Reputation: 30010
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?
Upvotes: 3