Transparent constexpr int as type identifier

I have a struct Foo

. I would like to add some kind of identifier (placeholder?) To statically select from a tuple of values ​​passed to various Foo

objects. Ideally, I would not become a template type because it causes a lot of changes elsewhere.

I tried adding an integer to it and using 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 to be able to use constexpr place()

in get<>

, what am I missing?

Do I have a way out without using templates?

+3


source to share


1 answer


The first blocker is that std :: get doesn't constexpr

, so even if it std::get<0>

works for you, it doesn't I need to. (Credit to @Nate Kohl)

You can try and write your own tuple

with an constexpr

accessor, but this approach won't work either. Each function constexpr

must also be called with no argument constexpr

(or constexpr this). There is currently no way to overload constexpr.



So bad luck. This is not possible in C ++ 11.

+1


source







All Articles