我可以将作用域枚举用于带有模板的C++标记调度吗?
模板新手在这里。我正在试验以下代码:
#include <type_traits>
enum class Thread
{
MAIN, HELPER
};
template<typename T>
int f()
{
static_assert(std::is_same_v<T, Thread::MAIN>);
return 3;
}
int main()
{
f<Thread::MAIN>();
}
换句话说,如果函数不是从主线程调用的,我想提出一个编译时断言。显然,编译器不接受枚举器作为模板参数,大喊大叫invalid explicitly-specified argument for template parameter 'T'。
我知道我可以使用两个结构作为标签:struct ThreadMain和struct ThreadHelper. 不幸的是,枚举 cass 已经在我的项目中随处使用,我宁愿避免重复。为此,我如何重用现有的枚举类?
回答
您现有的代码很接近。除了使用typename,您可以直接使用enum class名称作为非类型模板参数,如下所示:
template<Thread T>
int f()
{
static_assert(T == Thread::MAIN);
return 3;
}
你也必须改变static_assert。
- +1, However it would be better to use `N` for a *non-type* (value) template parameter like a common style with e.g. `template<int N>`. `T` parameter name may inaccurately suggest that this is a **T**ype parameter whereas it is not. Especially that his is not typical `enum` underlying type.