c++ - 为什么交换此代码中的模板参数可以修复错误?

标签 c++ templates

以下代码给出了没有匹配函数的错误

#include<iostream>
using namespace std;
using namespace std;
template<class T, class U>
void fn (T t) {
    cout<<t<<endl;
}

int main(int argc, const char * argv[]) {
    fn<int>(1);
    return 0;
}


C:\Users\tegra\Desktop\test.cpp||In function 'int main(int, const char**)':|
C:\Users\tegra\Desktop\test.cpp|9|error: no matching function for call to 'fn(int)'|
C:\Users\tegra\Desktop\test.cpp|9|note: candidate is:|
C:\Users\tegra\Desktop\test.cpp|4|note: template<class T, class U> void fn(T)|
C:\Users\tegra\Desktop\test.cpp|4|note:   template argument deduction/substitution failed:|
C:\Users\tegra\Desktop\test.cpp|9|note:   couldn't deduce template parameter 'U'|

但是,如果像这样交换模板参数,错误就会消失

#include<iostream>
using namespace std;
using namespace std;
template<class U, class T>
void fn (T t) {
    cout<<t<<endl;
}

int main(int argc, const char * argv[]) {
    fn<int>(1);
    return 0;
}

最佳答案

T可以从调用中的参数推断出来。 U不是。

当你写fn<int>时,您明确指定第一个参数为 int 。如果U是第一个参数,没有问题,因为T可以推论出。如果T但首先,编译器不知道什么 U应该是。

关于c++ - 为什么交换此代码中的模板参数可以修复错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418654/

相关文章:

c++ - 模 : The Purpose of An Undefined Integer

c++ - 用模板化类型指定模板化类型的类型

c++ - 如何在任意依赖类型上专门化模板

c++ - 在专门化之前使用模板?

c++ - 如果没有提供 Container::value_type,如何获取 C++ Container<T> 的 T?

c++ - 模板推导在堆上失败,但在堆栈上有效

c++ - memcpy() 给我段错误

c++ - 在C++中,如何在不使用if语句的情况下选择运行特定的成员函数?

c++ - 仅为某些 std::vector<T2> 类型启用模板

c++ - 为什么将 char 指针流式传输到 cout 不打印地址?