I m 试图根据使用<代码>的参数类型对功能模板进行专门化,类似于以下例子::https://en.cpp.com/w/cpp/types/enable_if
template<typename Type, typename Enabled = void>
void foo(Type t)
{
std::cout << "primary
";
std::cout << std::is_same<decltype(t), A>::value << "
";
}
template<typename Type, typename std::enable_if_t<std::is_same<Type, A>::value>::type>
void foo(Type t)
{
std::cout << "specialized
";
}
然而,在这种情况下,只有主要定义才被要求。 如果我试图与班级相同的话
template <class T, class Enable = void>
struct Foo
{
static void bar()
{
std::cout << "T is blah" << std::endl;
}
};
template <class T>
struct Foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
static void bar()
{
std::cout << "T is int" << std::endl;
}
};
它实现了理想行为:
int main() {
A a;
// not specializing
foo<A>(a); // primary called
foo(19); // primary called
// does specializing
Foo<int>::bar(); // int specialization is called
Foo<float>::bar(); // generic is called
return 0;
}
Could someone please explain this difference to me and if there is a way to achieve the desired behavior without use of classes?
My code example: https://godbolt.org/z/86jsxfqdG