功能专用模板问题 [英] Function specialized template problem

查看:135
本文介绍了功能专用模板问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是模板的新用户。我尝试定义专门的模板功能模板,但我的编译器返回错误。它是简单的最大功能,只写实践模板;这里是代码:

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

和专用功能:

 模板<> std :: string maximum< std :: string,std :: string>(std :: string prm1,std :: string prm2)
{
std :: cout< 内部专业功能
return(prm1.length()> prm2.length()?prm1:prm2);
}

如果我试图为std :: string或任何其他类型,包括我自己定义的类 - 错误总是相同:



错误C2912:显式专门化;'std :: string maximum(std :: string,std :: string)'不是函数模板的特殊化...



IntelliSense建议:没有函数模板实例

$



请提前感谢

class =h2_lin>解决方案

你忘了字符串前面的& 它期望参考类型,你的专业化是使用值类型。

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


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆