c++ 在lambda参数中使用type_identity_t

ubby3x7f  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(88)

我试图在一个表达式中重新实现Logan Smith的implicit_cast,我的方法是将一个匿名函数与type_identity_t结合起来:

#include <iostream>
using namespace std;
int main() {
  int i = 1;
  long j = 4;
  cout << max(j, []<class T>(type_identity_t<T> x) -> T { return x; }(i));
}

字符串
但它不起作用.编译器(gcc 13.2)抱怨说:

<source>: In function 'int main()':
<source>:6:70: error: no match for call to '(main()::<lambda(std::type_identity_t<T>)>) (int&)'
    6 |   cout << max(j, []<class T>(type_identity_t<T> x) -> T { return x; }(i));
      |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
<source>:6:18: note: candidate: 'template<class T> main()::<lambda(std::type_identity_t<T>)>'
    6 |   cout << max(j, []<class T>(type_identity_t<T> x) -> T { return x; }(i));
      |                  ^
<source>:6:18: note:   template argument deduction/substitution failed:
<source>:6:70: note:   couldn't deduce template parameter 'T'
    6 |   cout << max(j, []<class T>(type_identity_t<T> x) -> T { return x; }(i));
      |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~


它是可以挽救的吗?还是我应该换个方法?

z9gpfhce

z9gpfhce1#

正如视频中所解释的,这个implicit_cast必须用一个指定目标类型的显式模板参数来调用。你的lambda调用缺少这个。type_identity_t<T>的全部意义在于使它不会自动推导出T。它的存在是为了迫使用户显式指定模板参数。它没有任何其他功能效果。
要使用显式模板参数调用lambda,您需要编写

[]<class T>(type_identity_t<T> x) -> T { return x; }.operator()</*target type*/>(i)

字符串

相关问题