c++ - constexpr 技巧

标签 c++ metaprogramming constexpr

我认为这是不可能的,但我想在放弃之前问问你。

我想要类似 constexpr 增量的东西。

#include  <iostream>

constexpr int inc() {

  static int inc = 0;
  return inc++;
}

class Foo {

  static const int  Type = inc();
};

class Foo2 {

  static const int  Type = inc();
};

int main() {

  std::cout << "Foo1 " << Foo1::Type << st::endl;
  std::cout << "Foo2 " << Foo2::Type << st::endl;
  return 0;
}

我想将它调用到某些类中不是手动(为此我使用 CRTP),为每个类提供不同的类型,但类型必须是常量。 无论如何在 C++ 中实现类似的东西? (C++17 + TS)

最佳答案

所以 Filip Roseen 有解决方案称为 constant-expression counter :

#include  <iostream>

template<int N>
struct flag {
  friend constexpr int adl_flag (flag<N>);
};

template<int N>
struct writer {
  friend constexpr int adl_flag (flag<N>) {
    return N;
  }

  static constexpr int value = N;
};

template<int N, int = adl_flag (flag<N> {})>
int constexpr reader (int, flag<N>) {
  return N;
}

template<int N>
int constexpr reader (float, flag<N>, int R = reader (0, flag<N-1> {})) {
  return R;
}

int constexpr reader (float, flag<0>) {
  return 0;
}

template<int N = 1>
int constexpr next (int R = writer<reader (0, flag<32> {}) + N>::value) {
  return R;
}

class Foo {

  public:
    static const int  Type = next();
};

class Foo2 {

  public:
    static const int  Type = next();
};

int main() {

  std::cout << "Foo1 " << Foo::Type << std::endl;
  std::cout << "Foo2 " << Foo2::Type << std::endl;
  return 0;
}

谢谢大家:) 但是在我的主库中使用它太冒险了,每个项目都会用到它。

PS:如果还有其他答案,我现在不会关闭此问题。因为是的,它很丑。

关于c++ - constexpr 技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993441/

相关文章:

c++ - Constexpr 成员函数

c++ - 如何重新设计 C++ 类?

c# - 有没有使用代码模板的语言?

c++ - 如何在 Unix 中获取更改当前键盘布局的事件?

python - 在运行时向 python 添加模块

C++ 元编程 - 在代码中生成错误

c++ - 我什么时候可以确定 constexpr 全局变量是 "forgotten",就像 C 宏一样?

c++ - 创建一个 std::array,其大小在运行时计算

c++ - 如何从 boost::spirit::lex 标记确定行/列号?

c++ - 第二行列数较少 "cuts off"第一行列数较多