【问题标题】:How can a template function get max of an int or a char模板函数如何获得 int 或 char 的最大值
【发布时间】:2013-09-26 21:09:37
【问题描述】:
#include <iostream>
using namespace std;

template <class MyType>
MyType GetMax (MyType a, MyType b, MyType c) {
  return std::max(std::max(a, b), c);
}

int main () {
  int a = 5, b = 6, c = 7, d;
  char e [] = "1", f [] = "2", g [] = "3", h; 
  d=GetMax<int>(a,b,c);
  cout << d << endl;
}

错误:没有匹配函数调用 'GetMax(char [2], char [2], char [2])'

该程序在 int 上运行良好,但我不确定 char 的问题是什么

【问题讨论】:

  • 删除GetMax&lt;int&gt;(a,b,c)中的&lt;int&gt;,让它为你推断类型。此外,如果您将它与char*s 一起使用,它将比较指针而不是内容。如果您想比较字符串的内容,请使用std::string(或修改您的 func 以获取比较器)
  • 相关(因为std::max 不喜欢我的charint 比较):stackoverflow.com/questions/2304732/…

标签: c++


【解决方案1】:

您声明的是 C 风格的字符串,也不是 chars。

如果您想将GetMaxchars 一起使用,您的代码应该是这样的:

 char e = '1', f = '2', g = '3', h; 
 h = GetMax<char>(e, f, g);

请注意,在这种特殊情况下,编译器可以确定 GetMax 的签名,因此您可以将调用减少为:

 h = GetMax(e, f, g);

【讨论】:

  • char e = 1, f = 2, g = 3, h;。谁知道呢。
  • @DyP:当然——这也是可能的。
【解决方案2】:

char没有问题,char *有问题,也叫“c-style strings”。

c 风格的字符串 (char *) 没有 operator&lt;,所以 std::max 不起作用。您必须使用strcmp 自己实现它,或者改用std::string

【讨论】:

  • 实际上是的,有operator&lt; 用于指针,我认为问题是他明确指定了模板arg,而不是让它推断它或给出正确的类型
  • @kal 很好,有。但不是他想要的……:p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
相关资源
最近更新 更多