gpt4 book ai didi

c++ - 为什么 C++ 编译器不能推断模板参数?

转载 作者:太空狗 更新时间:2023-10-29 20:53:13 25 4
gpt4 key购买 nike

考虑以下示例:

template<typename TI>
char trunc(TI IN){
return (char)IN;
}

template <typename TO, typename TI>
TO applyf(TO (OP)(TI), TI IN){
return OP(IN);
}

template <typename TO, typename TI,
TO (OP)(TI)>
TO applyt(TI IN){
return OP(IN);
}

int main(){
int i = -21;
char r1 = applyf(trunc<int>, i);
char r2 = applyt<char, int, trunc>(i);
char r3 = applyt<trunc>(i);
}

当我用 g++(使用 C++11)编译这段代码时,出现错误:

Function.cpp:21:12: error: no matching function for call to 'applyt'

   char r3 = applyt<trunc>(i);

Function.cpp:13:4: note: candidate template ignored: invalid explicitly-specified argument for template parameter 'TO' TO applyt(TI IN){

所以我的问题很简单:输入参数类型很明显 - 一个 int - 对我来说 TO 应该很明显。

为什么TO和TI不能推断出来,但是在r1中可以推断出来?

最佳答案

trunc 是函数模板,不是类型,因此它不能匹配 typename TO

关于c++ - 为什么 C++ 编译器不能推断模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43461995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com