I have the following code:
#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包含许多类型时,这并不太优雅和实用。非常感谢您的帮助和建议。
i
也不是一个常量表达式。 - Rapptzsizeof(enum) == sizeof(std::underlying_type<enum>::type)
。 - Rapptz