A simplified example of my code:
namespace Example
{
class A
{
public:
template<typename T>
void foo(T &val);
template<>
void foo<long>(long &val);
};
template<typename T>
void A::foo(T &val)
{
std::cout << "Generic Function: " << val << std::endl;
}
template<>
void A::foo<long>(long &val)
{
std::cout << "Specialized Function: " << val << std::endl;
}
}
I get an error like:
explicit specialization in non-namespace scope
Why doesn't template specialization work here? How can I specify the behavior of a member function based on the type that's passed in?
1条答案
按热度按时间sc4hvdpw1#
You don't need specialization for this, simple overloading will work fine (ie, remove the
template<>
from the 2ndfoo()
), eg:Online Demo
Or, in C++17 and later, you can just get rid of the 2nd
foo()
altogether and useif constexpr
inside the implementation of the 1stfoo()
, eg:Online Demo