我认为这是不可能的,但我想在放弃之前问你一下。
我想要类似 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)
所以有解决方案菲利普·罗森 https://stackoverflow.com/users/1090079/filip-ros%C3%A9en-refp叫做常量表达式计数器 http://b.atch.se/posts/constexpr-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:如果有其他答案,我现在不会关闭它。因为是的,它很丑。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)