#include <functional>
#include <iostream>
template<typename T>
class MaybePtr{
T* ptr;
public:
MaybePtr(T* p) : ptr(p) {}
template <typename F,typename R = std::result_of<F(T*)>::type>
R Get(F access,F default){
if (ptr != nullptr)
return access(ptr);
else
return default(ptr);
}
};
template <typename T>
void f_void(T*) {}
int main(){
int * iptr = new int;
*iptr = 10;
auto m = MaybePtr<int>(iptr);
auto f = [](int* i) -> int {return *i + 1; };
auto f1 = [](int* i) -> int { return 0; };
int r = m.Get(f, f1); // error C2782
std::cout << f(iptr);
int i;
std::cin >> i;
}
Error
error C2782: 'R MaybePtr<int>::Get(F,F)' : template parameter 'F' is ambiguous
Why is F ambiguous? It should know that F is a function that takes a T* and returns a R.
A lambda with an empty closure may decay to a function pointer but here :
static_assert( std::is_same<decltype(f),decltype(f1)>::value,"different types" );
The error is normal, also Visual Studio is laxist, but you miss a typename
and default
is a reserved keyword.
template <typename F,typename R = typename std::result_of<F(T*)>::type>
A trick exists: force the lambda to decay to a function pointer. The below line compiles and does what you expect, of course, only valid with empty closure :
int r = m.Get(+f, +f1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With