【问题标题】:Constexpr tricksConsexpr 技巧
【发布时间】:2016-12-06 10:45:48
【问题描述】:

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

我想要一个类似 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),为它们中的每一个赋予不同的类型,但类型需要是 const。 反正有在 C++ 中实现类似的东西吗? (C++17 + TS)

【问题讨论】:

  • “我认为这是不可能的” 基本上使用 C++ 模板一切皆有可能,但有时它会变得非常复杂。
  • 我不确定,但我认为它可能是 C++17 的一部分,但我可能错了
  • 有非标准的COUNTER 宏,还有编译时副作用的实现(想到了Filip Roseen)。不过,后者非常丑陋。我宁愿尝试不同的方法。
  • 如果您不需要连续性,只需使用某个对象的地址作为唯一标识符即可。
  • 享受这种疯狂的乐趣:b.atch.se/posts/constexpr-counter(请不要这样做)

标签: c++ metaprogramming constexpr


【解决方案1】:

所以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:如果有其他答案,我现在不会关闭这个。因为是的,它很丑。

【讨论】:

    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 2010-11-10
    • 2010-09-13
    • 2011-07-18
    • 2011-10-30
    • 2018-05-26
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多