Search code examples
c++templatesc++11std-function

Deduce template-argument from std::function's return type


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>'
}

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?


Solution

  • 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.

    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();
    }