简体   繁体   中英

Function specialized template problem

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM