首页 > 解决方案 > 用推导类型声明类成员

问题描述

我有一个使用这样的类型推导的代码:

template <typename... Ttypes>
Tuple<Ttypes...> makeTuple(Ttypes... args) {
   Tuple<Ttypes...> result;
   fillTuple<0>(result, args...);
   return result;
}

我想将结果封装到一个不是类模板的类中。唯一的方法,这是合理的,是让它成为这样的static const成员:

struct A {
    static const auto t = makeTuple(1,2,3,'c');
};

我得到:error: in-class initializer for static data member of type 'const Tuple<int, int, int, char>' requires 'constexpr' specifier static const auto tuple = makeTuple(1,2,3,'c');

如果我使用

struct A {
    static const auto constexpr t = makeTuple(1,2,3,'c');
};

我明白了error: constexpr variable 'tuple' must be initialized by a constant expression

此外,使用constexpr对我不利,因为我喜欢在元组中使用非文字类型。

带有 -std=c++14 的编译器 Clang。

有没有办法得到我想要的?

标签: c++

解决方案


沿着这些思路,也许:

struct A {
    using TupleType = decltype(makeTuple(1,2,3,'c'));
    static const TupleType  t;
};

// In a .cpp file
const A::TupleType A::t = makeTuple(1,2,3,'c');

稍微复杂一些,但避免一些重复:

struct A {
    static auto MakeMyTuple() { return makeTuple(1,2,3,'c'); }
    using TupleType = decltype(MakeMyTuple());
    static const TupleType t;
};

// In a .cpp file
const A::TupleType A::t = A::MakeMyTuple();

这样,论据makeTuple都在一个地方。


推荐阅读