Search code examples
c++templatesresult-of

How to use std::result_of when return value is a template type?


I'm trying to use result_of for the case when Callable returns template type and get the following error (clang++). I also included a simple case where everything works fine.

Error:

main.cpp:22:50: note: candidate template ignored: could not match '<type-parameter-0-1>' against 'std::__1::shared_ptr<int> (*)()'
typename std::result_of<FunctionType<T>()>::type submit(FunctionType<T> f) {

Code:

    int f() {
      int x = 1;
      return x;
    }

    template<typename T>
    std::shared_ptr<T> g() {
      std::shared_ptr<T> x;
      return x;
    }

    template <template<typename> class FunctionType, typename T>
    typename std::result_of<FunctionType<T>()>::type submit(FunctionType<T> f) {

      using result_type = typename std::result_of<FunctionType<T>()>::type;

      result_type x;
      return x;
    }

      template<typename FunctionType>
      typename std::result_of<FunctionType()>::type submit2(FunctionType f) {

        using result_type = typename std::result_of<FunctionType()>::type;

        result_type x;
        return x;
     }


    int main()
    {   
      submit(g<int>);  // error
      submit2(f);       // ok

      return 0;
    }

Solution

  • g<int> is of type shared_ptr<int>() which when deduced by the function decays to a pointer to that type (shared_ptr<int>(*)()). FunctionType in submit is therefore not a template and you can't use template arguments on it.

    If you could be more clear about what you're trying to do we can figure out a solution to your main issue.