Function specialized template problem

江枫思渺然 提交于 2019-12-10 16:46:53

问题


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.



来源:https://stackoverflow.com/questions/4233519/function-specialized-template-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!