c++ - 如何强制编译器识别模板函数中的 lambda 类型?

标签 c++ templates c++11 lambda function-pointers

这是一个完整的小程序。前三个电话 test1()test2()编译运行正常,最后调用test2()不编译。如何让编译器识别对 test2() 的调用而不指定调用中的类型?

#include <functional>
#include <iostream>

// using function pointer
template <typename T>
T test1(T arg, T (*fnptr)(T)) {
  return fnptr(arg);
}

// using a lambda
template <typename T>
T test2(T arg, std::function<T (T)> mapfn) {
  return mapfn(arg);
}

int dbl(int v) {
  return 2 * v;
}

int main() {
  // v1a: compiles, runs without error
  int v1a = test1<int>(11, dbl);
  std::cout << v1a << std::endl;

  // v2a: compiles, runs without error
  int v2a = test2<int>(11, [=](int arg) { return 2 * arg; });
  std::cout << v2a << std::endl;

  // v1b (without template type): compiles, runs without error
  int v1b = test1(11, dbl);
  std::cout << v1b << std::endl;

  // v2a (without template type): doesn't compile: no matching fn
  int v2b = test2(11, [=](int arg)->int { return 2 * arg; });
  std::cout << v2b << std::endl;

  return 0;
}

编译器生成以下消息:

$ g++ -O3 -Wall -std=c++11 -o sketch_tiny sketch_tiny.cpp 
sketch_tiny.cpp:34:13: error: no matching function for call to 'test2'
  int v2b = test2(11, [=](int arg)->int { return 2 * arg; });
            ^~~~~
sketch_tiny.cpp:12:3: note: candidate template ignored: could not match
      'function<type-parameter-0-0 (type-parameter-0-0)>' against '<lambda at
      sketch_tiny.cpp:34:23>'
T test2(T arg, std::function<T (T)> mapfn) {
  ^
1 error generated.

有没有办法让编译器识别对 test2(...) 的调用不使用test2<int>(...)类型说明符?

就其值(value)而言,这是编译环境:

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix

最佳答案

模板参数推导仅查看非常有限的一组隐式转换。 lambda 不是 std::function ,因此模板参数推导失败。

通常有两种方法可以解决这个问题:

  1. 将 lambda 类型作为单独的模板参数:

    template <typename T, typename F>
    T test2(T arg, F mapfn) {
      return mapfn(arg);
    }
    

    这是最有效的方法。

  2. 如果由于某种原因您确实想使用 std::function并支付相关的类型删除费用,您可以将std::function<T(T)>进入非推导的上下文。

    template <typename T> struct identity { using type = T; };
    template <typename T> using non_deduced = typename identity<T>::type;
    
    template <typename T>
    T test2(T arg, non_deduced<std::function<T (T)>> mapfn) {
      return mapfn(arg);
    }
    

关于c++ - 如何强制编译器识别模板函数中的 lambda 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202377/

相关文章:

c++ - const 引用与 const char* 返回的 STL 字符串

c++ - 如何实现返回 protected 结构的私有(private)函数

c++ - 没有 "using"的模板基类的访问属性

C++11 - 编译时多态性解决方案

c++11 - 在签名中使用另一个成员模板函数的外线成员模板函数定义

c++ - 在什么情况下从流(的末尾)读取会导致停顿?

c++ - ->h_addr_list[0] 是我需要的地址吗?

c++ - 从子构造函数(模板)访问父成员

c++ - 如何为这个自定义 C++ List 类实现删除函数?

c++ - 如何通过模板参数推导避免衰减