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?
Your existing code is close. Instead of using
typename, you can just use theenum classname directly, as a non-type template parameter, like this:You have to change the
static_assertas well.