c++ - 如何在编译时查询 constexpr std::tuple?

标签 c++ c++11 constants tuples

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

#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,例如通过

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

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

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

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

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

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

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

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

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

编译正常,但是

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

不是吗?

提前非常感谢! - 拉尔斯

最佳答案

std::get 未标记为 constexpr,因此您不能使用它从 中的 tuple 中检索值constexpr 上下文,即使该元组本身就是 constexpr

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

关于c++ - 如何在编译时查询 constexpr std::tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5087364/

相关文章:

java - 除以减法 - 将余数除以减法?

c++ - Visual Studio unordered_set 异常,适用于 Codeblocks

c++ - 如何修改 const int 值 C++

c# - 计算机如何在类型之间进行转换

c++ - 如何将几个变量复制到其他变量?

c++ - 如何防止通过 'new' 运算符分配类? (我想确保我的 RAII 类始终分配在堆栈上。)

c++ - 重新排序可变参数

c++ - 为什么这个专门用于 basic_ifstream 模板的 char_traits<uint8_t> 和 codecvt<uint8_t> 会抛出 std::bad_cast?

C - 动态整数数组错误(代码 :Blocks/Visual Studio)

c# - 为什么要编译?