mardi 3 octobre 2017

c++ universal reference deduction failed on template function argument

#include <iostream>
#include <type_traits>
#include <utility>

template <class T> T id(T t) { return t; }
int id0(int t) { return t; }

template <class F, class T>
typename std::result_of<F(T)>::type f(F&& f, T&& t)
{
  return std::forward<F>(f)(std::forward<T>(t));
}

int main()
{
  {
    std::cout << f(id<int>, 1) << std::endl; // why failed ??? 
    std::cout << f(id0, 1) << std::endl;
  }
}

The first line will fail to compile with the following error messages.

error: no matching function for call to 'f'
    std::cout << f(id<int>, 1) << std::endl;
                 ^
note: candidate template ignored: substitution failure [with F = int (int), T = int]: function cannot return function type
      'int (int)'
typename std::result_of<F(T)>::type f(F&& f, T&&  t)

But here I don't quite understand why such difference will occur. Note that id0 and id<int> are basically the same functions after plugging in the template parameter.

Thus I am wondering what is really happening for the first case?

Thanks,

Aucun commentaire:

Enregistrer un commentaire