#include template class MaybePtr{ T* ptr; public: MaybePtr(T* p) : p...">

Pattern parameter "F" is ambiguous

#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; } 

Mistake

 error C2782: 'R MaybePtr<int>::Get(F,F)' : template parameter 'F' is ambiguous 

Why is F ambiguous? He should know that F is a function that takes T * and returns R.

+7
c ++ c ++ 11
source share
1 answer

An empty lambda may break into 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 a laxist, but you will skip typename and default is the reserved keyword.

 template <typename F,typename R = typename std::result_of<F(T*)>::type> 

There is a trick: getting lambda to decay into a function pointer. Below the line compiles and does what you expect, of course, only with an empty closure:

 int r = m.Get(+f, +f1); 
+12
source share

All Articles