Function specialized template problem

2019-06-27 23:46发布

问题:

I am new to templates. I try to define specialized template for function template, but my compiler returns error. It is simple max function, written just to practice templates; here's the code:

template <typename TYP1, typename TYP2> TYP1 maximum(TYP1& param1, TYP2& param2)
{
    return (param1 > param2 ? param1 : param2);
}

and specialized function:

template<> std::string maximum<std::string, std::string>(std::string prm1, std::string prm2)
{
    std::cout << "Inside specialized functiion\n";
    return (prm1.length() > prm2.length() ? prm1 : prm2);
}

It doesn't matter if I try to write specialization for std::string or any other type, including my own defined classes - the error is always the same:

"error C2912: explicit specialization; 'std::string maximum(std::string,std::string)' is not a specialization of a function template ... "

IntelliSense suggest: "no instance of function template"

What should I change to make this compile and work properly?

Thanks in advance

回答1:

You're forgetting the & in front of the strings. It expects reference types, your "specialization" is using value types.

template<> std::string maximum<std::string, std::string>(std::string &prm1, std::string &prm2)


回答2:

It's not a specialization because the primary template expects TYP1& and TYP2& parameters. You can fix your code by using :

template<> std::string maximum<std::string, std::string>(std::string &prm1, std::string &prm2)
{
    std::cout << "Inside specialized functiion\n";
    return (prm1.length() > prm2.length() ? prm1 : prm2);
}

Notice the parameters are taken by reference there.