Can I use a scoped enum for C++ tag dispatch with templates?

拈花ヽ惹草 提交于 2021-01-27 21:29:46

问题


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>();
}

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'.

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?


回答1:


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;
}

You have to change the static_assert as well.



来源:https://stackoverflow.com/questions/65618471/can-i-use-a-scoped-enum-for-c-tag-dispatch-with-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!