我有以下代码:
#include <cstdlib>
#include <cstdio>
#include <atomic>
enum ATYPE { Undefined = 0, typeA, typeB, typeC };
template<ATYPE TYPE = Undefined>
struct Object
{
Object() { counter++; }
static std::atomic<int> counter;
};
template<ATYPE TYPE>
std::atomic<int> Object<TYPE>::counter(1);
template<ATYPE TYPE>
void test()
{
printf("in test\n");
Object<TYPE> o;
}
int main(int argc, char **argv)
{
test<typeA>();
printf("%d\n", Object<typeA>::counter.load());
Object<typeA>::counter.store(0);
for (int i = 0; i < sizeof(ATYPE); ++i) {
Object<static_cast<ATYPE>(i)>::counter.store(0);
}
return 0;
}
当我使用以下命令行编译时:
clang++ -o test -std=c++11 -stdlib=libc++ test.cpp
我收到以下错误:
test.cpp:32:20: error: non-type template argument is not a constant expression
Object<static_cast<ATYPE>(i)>::counter.store(0);
^~~~~~~~~~~~~~~~~~~~~
test.cpp:32:39: note: read of non-const variable 'i' is not allowed in a constant expression
Object<static_cast<ATYPE>(i)>::counter.store(0);
^
testray.cpp:31:18: note: declared here
for (int i = 0; i < sizeof(ATYPE); ++i) {
我理解我相信的问题。模板的参数需要是 constexpr 而 i 显然不是。所以问题是,我是否可以做一些改变来让它发挥作用。通过这种工作,我的意思是,除了手动执行之外,我能否以某种更好的方式从该模板类中为 ATYPE 中的每种类型重置这些静态计数器:
Object<Undefined>::counter.store(0);
Object<typeA>::counter.store(0);
...
当 ATYPE 包含许多类型时,这不是那么优雅和实用。
非常感谢您的帮助和建议。