Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent constexpr int as type id

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?

like image 220
NickV Avatar asked Dec 01 '25 14:12

NickV


1 Answers

The first blocker is that std::get isn't constexpr, so even if std::get<0> works for you, it doesn't have to. (Credit to @Nate Kohl)

You can try hard and write your own tuple with constexpr accessor, but this approach will fail too. Every function that is constexpr also must be callable without a constexpr argument (or constexpr this). There is currently no way to overload on constexpr.

So, bad luck. This is impossible in C++11.

like image 84
ipc Avatar answered Dec 03 '25 05:12

ipc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!