模板化函数..错误:模板 ID 与任何模板声明都不匹配
我编写了一个函数模板和一个显式专用的模板函数,它只接受 3 个参数并计算其中最大的参数并打印它。
专用函数会导致错误,而模板则可以正常工作。 但我想使用 char* 类型。
这是我得到的错误=> 错误:模板 ID 'Max<>' for 'void Max(char, char, char)' 与任何模板声明都不匹配
以下是我的代码:
template <typename T>
void Max(T& a,T& b,T& c)
{
if(a > b && a >> c)
{
cout << "Max: " << a << endl;
}
else if(b > c && b > a)
{
cout << "Max: " << b << endl;
}
else
{
cout << "Max: " << c << endl;
}
}
template <>
void Max(char* a,char* b,char* c)
{
if(strcmp(a,b) > 0 )
{
cout << "Max: " << a << endl;
}
else if(strcmp(b,c) > 0)
{
cout << "Max: " << b << endl;
}
else
{
cout << "Max: " << b << endl;
}
}
I have written a function template and an explicitly specialized templated function which simply takes in 3 arguments and calculates the biggest among them and prints it.
The specialized function is causing an error,whereas the template works fine.
But I want to work with char* type.
This is the error I get=>error: template-id ‘Max<>’ for ‘void Max(char, char, char)’ does not match any template declaration
Following is my code:
template <typename T>
void Max(T& a,T& b,T& c)
{
if(a > b && a >> c)
{
cout << "Max: " << a << endl;
}
else if(b > c && b > a)
{
cout << "Max: " << b << endl;
}
else
{
cout << "Max: " << c << endl;
}
}
template <>
void Max(char* a,char* b,char* c)
{
if(strcmp(a,b) > 0 )
{
cout << "Max: " << a << endl;
}
else if(strcmp(b,c) > 0)
{
cout << "Max: " << b << endl;
}
else
{
cout << "Max: " << b << endl;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要通过引用获取指针:
也就是说,最好不使用显式专门化,而只是重载函数:
专门化函数模板几乎总是一个坏主意。有关详细信息,请参阅 Herb Sutter 的“为什么不专门化函数模板?”
You need to take the pointers by reference:
That said, it would be better not to use an explicit specialization and instead just overload the function:
It's almost always a bad idea to specialize function templates. For more, see Herb Sutter's "Why Not Specialize Function Templates?"
我遇到了同样的问题并使用 typedef 修复了它:
I ran into the same problem and fixed it by using typedef: