Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

c++ - Tuple std::get() Not Working for Variable-Defined Constant

I have been having the following problem:

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;
}

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

However, the following works fine:

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?

Thanks!

EDIT: The difference is in the const int j = i; vs. const int j = 1;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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; is a compile time constant and can be used to instantiate the template as its value is known at compile time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...