c++ - 用推导类型声明类成员
问题描述
我有一个使用这样的类型推导的代码:
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。
有没有办法得到我想要的?
解决方案
沿着这些思路,也许:
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
都在一个地方。
推荐阅读
- java - 运行 lint 测试时出现 JAXBException
- karate - 当帖子 'content-type' 是 application/x-www-form-urlencoded 并且 * form field param= {
} - python - 有没有办法在 Azure Databricks 中动态地将参数传递给作业?
- c# - 如何使用 C# 将 `xmlns` 重命名为 TYPE
- python - django-celery 接收任务但不执行它
- javascript - elasticsearch中如何将url参数添加到elasticsearch UpdateByQuery
- google-apps-script - 当我在单元格 A1 中进行任何更改时,如何将单元格 A2 的值更改为“Today()”?
- php - 在使用 php 向用户显示之前更改网页内容
- c# - 转换为 JSON 时,@ 符号出现在 XML 的属性之前
- javascript - Vanilla Javascript 类中的“计算属性”