我目前正在尝试为显示不同值的功能的函数编写模板特化.我的代码是:
#include <iostream>
using namespace std;
template <class T>
T myfunc(T x)
{
return x*x;
}
template<>
string myfunc<string>(string ss)
{
return (ss+ss);
}
int main()
{
cout<<myfunc("test")<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译失败:
错误C2784:'std :: _ String_iterator <_Mystr> std :: operator +(_ String_iterator <_Mystr> :: difference_type,std :: _ String_iterator <_Mystr>)':无法推断'std :: _ String_iterator <_Mystr>'的模板参数来自'std :: string'
你能帮我检查一下究竟是什么问题吗?
您需要将函数传递给字符串,而不是char数组.尝试myfunc(string("test"))
稍微扩展一下 - 在调用函数时选择使用哪个模板/模板专门化称为模板参数推导.
您希望调用myfunc,但测试类型为char [5](结尾为空字符).因此,模板参数被'推导'为char [5].
通常,char []可以在调用完全专用的函数(不是模板函数)时隐式地转换为字符串(我相信这是不推荐使用的).这个隐式转换是因为,正如user1274223指出的那样,std :: string有一个带有签名字符串(const char*)的构造函数,并且这个构造函数不是显式的!当我们想要假装c字符串(char*)可以与cplusplus strings(std::string)轻松互换时,这很有用,但是在这些类型的情况下它可能会令人困惑.
另一个解决方法是myfunc<string>("test"),因为这里直接传递模板参数,并且可以隐式地转换 char [] .
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |