【问题标题】:Explicit specialization - template-id does not match any template declaration显式特化 - 模板 ID 不匹配任何模板声明
【发布时间】:2017-07-23 13:03:20
【问题描述】:

我对 C++ 程序中的显式专业化有疑问

我想对 char* 类型进行专门化,将地址返回到最长的 char 数组,但我不断收到错误:

C:\Users\Olek\C++\8_1\main.cpp|6|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|
C:\Users\Olek\C++\8_1\main.cpp|38|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|

这是程序的代码

#include <iostream>

template <typename T>
T maxn(T*,int);

template <> char* maxn<char*>(char*);

const char* arr[5]={
    "Witam Panstwa!",
    "Jak tam dzionek?",
    "Bo u mnie dobrze",
    "Bardzo lubie jesc slodkie desery",
    "Chociaz nie powinienem",
};

using namespace std;

int main()
{
    int x[5]={1,4,6,2,-6};
    double Y[4]={0.1,38.23,0.0,24.8};
    cout<<maxn(x,5)<<endl;
    cout<<maxn(Y,4)<<endl;
    return 0;
}

template <typename T>
T maxn(T* x,int n){
    T max=x[0];
    for(int i=0;i<n;i++){
        if(x[i]>max)
            max=x[i];
    }
    return max;
}

template <>
char* maxn<char*>(char* ch){
    return ch;
}

我还没有实现这个函数,但是它已经被声明了。另外我认为使用函数重载会更容易,但它是一本书的分配。

提前感谢您的回答。

【问题讨论】:

  • 您希望template &lt;&gt; char* maxn&lt;char*&gt;(char*); 专注于哪个模板?
  • maxn 模板,模板 T maxn(T* x,int n)
  • 哦,等等,我还应该添加第二个参数吗? (int n)?。它也不起作用

标签: c++ c++11 templates specialization explicit


【解决方案1】:

您的模板返回 T 类型并采用 T* 类型,但您的专业化返回的类型与其所采用的类型相同,因此不匹配。

如果您专注于T=char*,那么它需要接受一个 T* (char**) 并返回一个 char*,或者改为专注于 char

template <typename T>
T maxn(T*,int);

template <> char maxn<char>(char*, int);
template <> char* maxn<char*>(char**, int);

int main() {
    char * str;
    maxn(str, 5);
    maxn(&str, 6);
}

【讨论】:

  • 感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多