无法推导'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?
如果您向编译器传递了的实际实例,则编译器只能从
;传递lambda无效,因为lambda不是 f
推导出 R
std :: function< R(T)> 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();
}