模板参数推导/替换失败 C++

template argument deduction/substitution failed c++

本文关键字:替换 失败 C++ 参数      更新时间:2023-10-16

我有三个文件: 主要:

#include <iostream>
#include "Punkt.h"
int main() {
const Punkt s1(0, 1);
const Punkt s2(-5, 2);
std::cout << "s1 " << s1.wsp<0>() <<  " " << s1.wsp<1>() << std::endl;
}

页眉:

#include <iostream>
#pragma once
class Punkt{
public:
Punkt(int x, int y){
m_x = x;
m_y = y;
}
template <typename T> int wsp() const;
private:
int m_x;
int m_y;
};

.cpp:

#include "Punkt.h"
#include <iostream>
using namespace std;
template <typename T> 
int Punkt::wsp() const
{
int obiekt(T);
try{
if (obiekt==1){
return m_y;
}
if (obiekt==0){
return m_x;
}
throw;
}
catch(...){
std::cout << "Incorrect number" << std::endl;
}
}

问题在于:

Main.cpp:46:35: error: no matching function for call to ‘Punkt::wsp() const’
std::cout << "s1 " << s1.wsp<0>() <<  " " << s1.wsp<1>() << std::endl;
In file included from Main.cpp:39:0:
Punkt.h:11:28: note: candidate: template<class T> int Punkt::wsp() const
template <typename T> int wsp() const;
Punkt.h:11:28: note:   template argument deduction/substitution failed:

我从模板开始,我不明白发生了什么。 当我将 wsp 更改为:"模板"(和功能 ofc(时,它工作正常。 有人知道吗?

在编写模板时,typename不仅仅是您放在模板参数前面的随机关键字,它具有特定的含义。

将模板参数视为编译时参数。像所有参数一样,它们具有类型和名称typename意味着模板参数的类型将是某个运行时类型的名称。

因此,当您声明:

template <typename T> int wsp() const;

你的意思是:

"wsp 是接受一个名为 T 的单个编译时参数的函数,该参数将是一个类型的名称">

当你调用wsp<1>()时,编译器会告诉你:"嘿!1不是类型的名称!你告诉我wsp<typename>,这毫无意义。

解决此问题很容易,您只需将模板参数的类型从typename更改为int.

template <int T> int wsp() const;

由于wsp是一个模板,解析器会混淆它是某个表达式(wsp < 0) > ()还是带有模板参数的函数。这就是为什么您需要指定obj.template wsp<0>()来消除这两种情况之间的歧义。