函数模板的 C++ 问题(未找到实例)

标签 c++ c++11 templates

    template<typename T, int P>
    T matematika(T polje[], int N) {
      //CODE...
    }

这就是错误所在(没有函数模板“matematika”的实例匹配指定的类型)

template<>
string matematika(string polje[], int N) {     // ERROR
  //CODE...
}

最佳答案

特化模板的正常语法要求您在特化声明中的名称后面提供特化的模板参数。示例:

template <class T>
struct Container {};

template <>
struct Container<int> {};

当特化一个函数模板(并且只是一个函数模板)时,如果参数可以从特化中推导出来,则可以省略它们。情况就是这样,例如这里:

template <class T>
void foo(T t) {}

// One valid way to specialise:
template <>
void foo<int>(int i) {}

// Another valid way to specialise:
template <>
void foo(int i) {}

但是,这仅适用于可以从特化中推导出模板参数的情况。在您的情况下,情况并非如此,因为没有什么可以从中推断出 P 。因此,您必须明确提供该值:

template<>
string matematika<string, /*Whatever value of P you want to specialise for*/>(string polje[], int N) {
  //CODE...
}

关于函数模板的 C++ 问题(未找到实例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872720/

相关文章:

c++ - 填充指向 vector 的 vector

c++ - 在可变参数模板函数中连接字符串(和数字)

c++ - 使用模板重载功能

c++ - 如何自定义函数行为?

c++ - 扭曲的二项式系数

c++ - 模板函数采用任何仿函数并返回仿函数返回的类型

c++ - std::decay 和按值传递之间有什么区别?

c++ - 如何使模板函数成为模板类的 friend

c++ - 需要一个 constexpr 来使 for 循环中的值加倍

c++ - 在 C++ 中循环字符时出现意外结果