首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Constexpr花招

Constexpr花招
EN

Stack Overflow用户
提问于 2016-12-06 10:45:48
回答 1查看 1K关注 0票数 9

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

我想要一个像警察增量的东西。

代码语言:javascript
复制
#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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-06 11:11:25

所以有一个菲利普·罗森的解决方案叫做常数表达式计数器

代码语言:javascript
复制
#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:如果有其他的答案,我不会马上结束这件事。因为是的,它很丑。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40993441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档