如何在编译时查询 constexpr std::tuple? [英] How to query a constexpr std::tuple at compile time?

查看:40
本文介绍了如何在编译时查询 constexpr std::tuple?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++0x 中,可以创建一个 constexpr std::tuple,例如喜欢

In C++0x, one can create a constexpr std::tuple, e.g. like

#include <tuple>
constexpr int i = 10;
constexpr float f = 2.4f;
constexpr double d = -10.4;
constexpr std::tuple<int, float, double> tup(i, f, d);

也可以在运行时查询 std::tuple,例如通过

One also can query a std::tuple at runtime, e.g. via

int i2 = std::get<0>(tup);

但不能在编译时查询,例如,

But it is not possible to query it at compile time, e.g.,

constexpr int i2 = std::get<0>(tup);

会抛出编译错误(至少在最新的 g++ 中)快照 2011-02-19).

will throw a compilation error (at least with the latest g++ snapshot 2011-02-19).

还有其他方法可以在编译时查询 constexpr std::tuple 吗?

如果没有,是否存在不应该查询它的概念性原因?

And if not, is there a conceptual reason why one is not supposed to query it?

(我知道避免使用 std::tuple,例如,通过使用 boost::mpl或 boost::fusion 代替,但不知何故,不使用元组类听起来是错误的在新标准中...).

(I am aware of avoiding using std::tuple, e.g., by using boost::mpl or boost::fusion instead, but somehow it sounds wrong not to use the tuple class in the new standard...).

顺便问一下,有谁知道原因

By the way, does anybody know why

  constexpr std::tuple<int, float, double> tup(i, f, d);

编译正常,但是

  constexpr std::tuple<int, float, double> tup(10, 2.4f, -10.4);

不是吗?

提前非常感谢!- 拉尔斯

Thanks a lot in advance! - lars

推荐答案

std::get 没有标记 constexpr,所以你不能用它来从constexpr 上下文中的 tuple,即使该元组本身就是 constexpr.

std::get is not marked constexpr, so you cannot use it to retrieve the values from a tuple in a constexpr context, even if that tuple is itself constexpr.

不幸的是,std::tuple 的实现是不透明的,所以你也不能编写自己的访问器.

Unfortunately, the implementation of std::tuple is opaque, so you cannot write your own accessors either.

这篇关于如何在编译时查询 constexpr std::tuple?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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