Ignorant
Ignorant

Reputation: 2671

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

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?

Upvotes: 3

Views: 622

Answers (1)

Stephen Newell
Stephen Newell

Reputation: 7838

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.

Upvotes: 9

Related Questions