我可以在模板中使用带范围的枚举来分发C ++标签吗? [英] Can I use a scoped enum for C++ tag dispatch with templates?

查看:58
本文介绍了我可以在模板中使用带范围的枚举来分发C ++标签吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板新手.我正在尝试以下代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆