Search code examples
c++templatestemplate-meta-programmingstd-functiontype-deduction

std::function and function type deduced by "using" don't have same type


Here is a small example to show the difference of two function types that are not the same:

#include <iostream>
#include <functional>
#include <type_traits>

template <typename T>
using BinaryOperator = T(const T&, const T&);

int main() {

    std::cout << std::boolalpha 
              << std::is_same<
                      std::function<int(const int&, const int&)>, 
                      BinaryOperator<int>
                 >::value 
              << std::endl;

    return 0;
}

This prints false which is confusing to me. Both types seems to be equivalent. How are they different?


Solution

  • Both types seems to be equivalent. How are they different?

    Well... no: they are different types.

    If you look at the std::function's page in cppreference.com, you can see that std::function is a class with partial specialization (only the specialization is defined) declared as follows

    template <class>
    class function; // undefined
    
    template <class R, class... Args>
    class function<R(Args...)>;
    

    So your BynaryOperator<int> isn't equivalent to std::function<int(const int&, const int&)> but is equivalent to its template argument.

    You can see that is true

    std::is_same<std::function<int(const int&, const int&)>, 
                 std::function<BinaryOperator<int>>
    >::value //  ^^^^^^^^^^^^^^...................^