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
427 views
in Technique[技术] by (71.8m points)

c++ - How to query a constexpr std::tuple at compile time?

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

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

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

Is there any other way to query a constexpr std::tuple at compile time?

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

(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);

compiles fine, but

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

not?

Thanks a lot in advance! - lars

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

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


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

...