Constexpr技巧 [英] Constexpr tricks

查看:88
本文介绍了Constexpr技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是不可能的,但是我想在放弃之前询问您.

I think it's not possible but I'd like to ask you before give up about it.

我想要类似constexpr的增量.

I want something like a constexpr increment.

#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)

I want to call it into some classes not manually (I use CRTP for that), to give a different type to each of them, but the type need to be const. There is anyway to achieve something like that in C++? (C++17 + TS)

推荐答案

因此,有 Filip Roseen 称为常量表达式计数器:

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

PS: I won't close this right now if there is another answer. Because yes it's ugly.

这篇关于Constexpr技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆