我可以在模板中使用带范围的枚举来分发C ++标签吗? [英] Can I use a scoped enum for C++ tag dispatch with templates?
问题描述
模板新手.我正在尝试以下代码:
Template newbie here. I'm experimenting with the following code:
#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>();
}
换句话说,如果未从主线程调用该函数,我想提出一个编译时断言.显然,编译器不接受枚举数作为模板参数,对模板参数'T'的无效显式指定的参数大喊.
In words, I want to raise a compile-time assert if the function is not called from the main thread. Apparently the compiler doesn't accept an enumerator as template argument, yelling invalid explicitly-specified argument for template parameter 'T'
.
我知道我可以使用两个结构作为标记: struct ThreadMain
和 struct ThreadHelper
.不幸的是,枚举Cass已经在我的项目中到处使用,我希望避免重复.我该如何为此目的重用现有的枚举类?
I know I could use two structs as tags: struct ThreadMain
and struct ThreadHelper
. Unfortunately the enum cass is already used everywhere in my project and I'd prefer to avoid duplicates. How can I reuse the existing enum class for this purpose?
推荐答案
您现有的代码已关闭.代替使用 typename
,您可以直接使用 enum类
名称作为非类型模板参数,如下所示:
Your existing code is close. Instead of using typename
, you can just use the enum class
name directly, as a non-type template parameter, like this:
template<Thread T>
int f()
{
static_assert(T == Thread::MAIN);
return 3;
}
您还必须更改 static_assert
.
这篇关于我可以在模板中使用带范围的枚举来分发C ++标签吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!