透明constexpr int作为类型id

时间:2013-01-24 22:26:01

标签: c++ templates c++11

我有一个结构Foo。 我想添加一些id(占位符?)来静态选择传递给不同Foo对象的值元组。 理想情况下,我不会将其设为模板类型,因为它会在其他位置触发许多更改。

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

我原以为我可以使用constexpr place()中的get<>,我错过了什么?

我是否可以在不使用模板的情况下解决问题?

1 个答案:

答案 0 :(得分:1)

第一个拦截器是std::get不是constexpr,所以即使std::get<0>适合您,也不一定。 (感谢@Nate Kohl)

您可以尝试使用tuple访问者编写自己的constexpr,但这种方法也会失败。 每个函数constexpr必须可以在没有constexpr参数(或constexpr this)的情况下调用。目前没有办法在constexpr上重载。

所以,运气不好。这在C ++ 11中是不可能的。

相关问题