无法推导'std :: function'的模板参数 [英] Could not deduce template argument for 'std::function'

查看:66
本文介绍了无法推导'std :: function'的模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常从不写C ++,今天我尝试使用C ++模板进行实验.我实现了一个Maybe类型,看起来像这样

I usually never write C++ and today I tried experimented with C++ templates. I implemented a Maybe type which looks like this

#include <functional>
#include <iostream>
#include <string>
template<typename T>
class TMaybe
{
  T value;
public:
  TMaybe() : value(nullptr){}
  TMaybe(T &&v) : value(v){}
  TMaybe(T v) : value(v){}
};

template<typename T, typename R>
TMaybe<R> maybe_if(const TMaybe<T> &m, std::function<R(T v)> f){
  return (m.value != nullptr) ? TMaybe<R>(f(m)) : TMaybe();
}

int main(){
  int i = 10;
  auto m = TMaybe<int>(i);
  auto plus_ten = [](int i) -> int {return i + 10;};
  maybe_if(m, plus_ten); // could not deduce template argument for 'std::function<R(T)>' from 'main::<lambda_17413d9c06b6239cbc7c7dd22adf29dd>'
}

,但错误消息无法推断出'std :: function< R(T)>'的模板参数来自"main ::< lambda_17413d9c06b6239cbc7c7dd22adf29dd>" 的帮助不是很大.您能发现错误吗?

but the error message could not deduce template argument for 'std::function<R(T)>' from 'main::<lambda_17413d9c06b6239cbc7c7dd22adf29dd>' is not very helpful. Can you spot the error?

推荐答案

如果您向编译器传递了的实际实例,则编译器只能从 f 推导出 R std :: function< R(T)> ;传递lambda无效,因为lambda不是 std :: function 专业化的实例.

The compiler can only deduce R from f if you pass it an actual instance of std::function<R(T)>; passing a lambda won't work, as a lambda isn't an instance of a std::function specialization.

编写代码的正确方法是允许任何仿函数类型,并从中推断出 R :

The correct way to write your code is to allow any functor type, and deduce R from it:

template<typename T, typename F, typename R = typename std::result_of<F(T)>::type>
TMaybe<R> maybe_if(const TMaybe<T> &m, F f){
  return (m.value != nullptr) ? TMaybe<R>(f(m.value)) : TMaybe();
}

这篇关于无法推导'std :: function'的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆