问题
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