gpt4 book ai didi

c++ - 模板函数..错误 : template-id does not match any template declaration

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:55 30 4
gpt4 key购买 nike

我已经编写了一个函数模板一个明确专门化的模板函数,它只接受 3 个参数并计算其中最大的参数并打印出来。

专用函数导致错误,而模板工作正常。但我想使用 char* 类型

这是我得到的错误=> error: template-id ‘Max<>’ for ‘void Max(char, char, char)’ does not match any template declaration

以下是我的代码:

    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;
}
}

最佳答案

您需要通过引用获取指针:

template <> 
void Max(char*& a,char*& b,char*& c)

也就是说,最好不要使用显式特化,而只是重载函数:

void Max(char* a, char* b, char* c)

专门化函数模板几乎总是一个坏主意。有关更多信息,请参阅 Herb Sutter 的 "Why Not Specialize Function Templates?"

关于c++ - 模板函数..错误 : template-id does not match any template declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3934933/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com