I have a struct Foo.
I would like to add some kind of id (placeholder ?) to statically select from a tuple of values passed to different Foo objects.
Ideally I would not make it a template type because it will trigger many changes in other locations.
I tried adding an integer to it and use constexpr expressions (Demo)
#include <tuple>
using namespace std;
struct Foo {
private:
const int pl;
public:
constexpr Foo (int c) : pl(c) {}
constexpr int place() {return pl;}
template <typename... T>
constexpr int extract(std::tuple<T ...> const &vals) {
// I would like to uncomment the following but it fails compiling
// return std::get<pl>(vals);
return std::get<0>(vals);
}
};
int main(void) {
constexpr Foo f(1);
constexpr std::tuple<int, int> test = std::make_tuple(0, 10);
// The following passes
static_assert(f.place() == 1, "ERROR");
// The following fails
static_assert(f.extract(test) == 10, "ERROR");
}
I was expecting that I could use the constexpr place() in the get<>, what am I missing?
Do I have a way out without using templates?
The first blocker is that std::get isn’t
constexpr, so even ifstd::get<0>works for you, it doesn’t have to. (Credit to @Nate Kohl)You can try hard and write your own
tuplewithconstexpraccessor, but this approach will fail too. Every function that isconstexpralso must be callable without aconstexprargument (or constexpr this). There is currently no way to overload on constexpr.So, bad luck. This is impossible in C++11.