简体   繁体   English

编译器无法推断基本功能中的模板参数

[英]Compiler can't deduce template parameter in basic function

I have a template function, whose type depends on type parameters. 我有一个模板函数,其类型取决于类型参数。 The compiler can't deduce template parameter even if it's obvious. 即使很明显,编译器也无法推断出模板参数。 This is a basic code and even here it doesn't know it is an int ( int is just example). 这是一个基本代码,即使在这里它也不知道它是一个intint只是示例)。 What should be changed to make it work? 应该进行哪些更改才能使其正常工作?

#include <iostream>
using namespace std;

template<class T1, class T2>
T1 pr (T2 w) {
    return int(w);
}

int main() {
cout<<pr('A');  // your code goes here
    return 0;
}

Compiler can only deduce template type arguments only from function arguments types, not from result type. 编译器只能从函数参数类型推断出模板类型参数,而不能从结果类型推断出模板类型参数。 To make it work without changing function template you need to explicitly specify type argument: 要使其工作而不更改功能模板,您需要显式指定type参数:

cout << pr<int>('A');

But it is probably better to change the definition, since T1 parameter doesn't seem to be useful: 但是更改定义可能更好,因为T1参数似乎没有用:

template<class T>
int pr (T w){
    return int(w);
}

In C++11 you can use trailing return type, which might be useful in more complex situations: 在C ++ 11中,可以使用尾随返回类型,这在更复杂的情况下可能很有用:

template<class T>
auto pr (T w) -> decltype(int(w)) {
    return int(w);
}

And finally C++14 has return type deduction, so ther it is simply: 最后,C ++ 14具有返回类型推导,因此它很简单:

template<class T>
auto pr (T w) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么编译器不能从返回类型中推导出模板参数? - Why can't the compiler deduce template parameter from return type? 为什么编译器不能推导出这个简单函数的模板参数? - Why can't the compiler deduce template argument for this simple function? 无法推断模板参数 - Can't deduce template parameter c++ 模板参数编译器无法推断 - c++ template parameter compiler can not deduce 为什么 GCC 编译器不能以别名模板形式从 std::array 推导出模板参数之一 - Why can't GCC compiler deduce one of the template parameter from std::array in alias template form 为什么编译器在与转换运算符一起使用时不能推导出模板参数? - Why can't the compiler deduce the template parameter when used with a conversion operator? 为什么编译器不能推导出自动模板参数,除非我添加const? - Why can't the compiler deduce auto template parameter unless I add const? 如果参数类型取决于模板参数,为什么编译器不能推断返回类型 - Why can't the compiler deduce the return type if argument type depends on a template parameter 为什么在零数组的情况下编译器不推导template参数? - Why a compiler doesn't deduce the template parameter in case of zero array? g ++编译器错误:无法推断模板参数'_Funct' - g++ compiler error: couldn't deduce template parameter ‘_Funct’
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM