元组 std::get() 不适用于变量定义的常量

2022-01-13 00:00:00 type-conversion constants c++

我遇到了以下问题:

std::tuple<Ts...> some_tuple = std::tuple<Ts...>();
for (int i = 0; i < 2; i++) {
  const int j = i;
  std::get<j>(temp_row) = some_value;
}

不编译:(在 xcode 中)它说没有匹配的函数调用 'get'".

Does not compile: (in xcode) it says " no matching function call for 'get' ".

但是,以下工作正常:

std::tuple<Ts...> some_tuple = std::tuple<Ts...>();
for (int i = 0; i < 2; i++) {
  const int j = 1;
  std::get<j>(temp_row) = some_value;
}

是否与将常量的值定义为变量的值有关?

Does it have something to do with defining the value of a constant to be the value of a variable?

谢谢!

区别在于 const int j = i;const int j = 1;

推荐答案

这里的问题是 C++ 有两种不同的常量.有编译时常量和运行时常量.编译时常量是在编译时已知的常量,并且是唯一可以在模板中使用或用作数组大小的有效常量.运行时常数是一个不能改变的值,但该值是在运行时才知道的.这些常量不能用作模板或数组大小的值.所以在

The problem here is C++ has two different kinds of constants. There are compile time constants and there are run time constants. A compile time constant is a constant that is know at compile time and is the only valid constant that can be used in a template or as an array size. A run time constant is a value that cannot change but the value is something that is not known until run time. These constants cannot be used as a value for a template or an array size. So in

std::tuple<Ts...> some_tuple = std::tuple<Ts...>();
for (int i = 0; i < 2; i++) {
  const int j = i;
  std::get<j>(temp_row) = some_value;
}

i 是一个运行时值,它使 j 成为运行时常量,您不能用它实例化模板.然而在

i is a run time value which makes j a run time constant and you cannot instantiate a template with it. However in

std::tuple<Ts...> some_tuple = std::tuple<Ts...>();
for (int i = 0; i < 2; i++) {
  const int j = 1;
  std::get<j>(temp_row) = some_value;
}

const int j = 1; 是编译时常量,可用于实例化模板,因为其值在编译时已知.

const int j = 1; is a compile time constant and can be used to instantiate the template as its value is known at compile time.

相关文章