Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 332
Overpain Avatar asked Dec 13 '22 18:12

Overpain


2 Answers

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)
like image 147
wheaties Avatar answered Jan 01 '23 09:01

wheaties


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.

like image 22
icecrime Avatar answered Jan 01 '23 09:01

icecrime