程序无法调用专门的模板实现

时间:2018-11-11 00:02:30

标签: c++ templates

我正在尝试学习C ++模板。当我运行以下示例时,该程序无法调用专用模板实现。因此,我得到了错误的输出。有人可以告诉原因吗?

Lines <- "subject  condition  value
01       A          12
01       A          6
01       B          10
01       B          2
02       A          5
02       A          11
02       B          3
02       B          5
02       B          9"
DF <- read.table(text = Lines, header = TRUE, strip.white = TRUE,
  colClasses = c("character", "character", "numeric"))

2 个答案:

答案 0 :(得分:2)

参数作为常量char传递。因此,请尝试以下代码。请注意,我还包括了必要的头文件。此外,强烈建议使用std::coutusing std::cout;

#include <iostream> 
#include <cstring> 

template <class T> 
T max(T a, T b) 
{ 
    std::cout << "2 ..." << std::endl; 
    return a > b ? a : b; 
} 

template<> 
const char* max(const char* a, const char* b) 
{ 
    std::cout << "1 ..." << std::endl; 
    return std::strcmp(a, b) > 0 ? a : b; 
} 

int main() 
{ 
    std::cout << max("Aladdin", "Jasmine") << std::endl; 
    return 0; 
}

答案 1 :(得分:0)

您看到此问题的原因是,您传递的参数类型为char const *(也可以拼写为const char *)。在C ++中,我不知道有任何标准方法可以打印出类型的全名。但是有一种方法可以测试这种事情。

模板的问题之一是系统将扩展它可以扩展的任何模板。因此,您将以某种方式使代码神秘地工作,而不能完全确定为什么。在这种情况下,您可以让编译器准确告诉您问题的一种方法是尝试删除模板:

#include <iostream>
#include <cstring>

using ::std::cout;
using ::std::strcmp;

char* max(char* a, char* b)
{
    cout << "1 ..." << '\n'; // Don't use ::std::endl Use cerr if you need flushing.
    return strcmp(a, b) > 0 ? a : b;
}
int main()
{
    cout << max("Aladdin", "Jasmine") << '\n';
    return 0;
}

编译器会帮助您告诉您,您正在尝试调用一个将非const参数与const参数一起使用的函数,您将确切地了解问题所在。