Search code examples
c++templatesfunction-object

Having Function Objects Auto Detect Type in c++


I wanted to sort a vector containing ints in reverse order, but since I had gotten so used to type deduction in c++ I had passed the function object greater<>() without specifying int, since what else could it be? This did not work using g++, but did work with the visual studio compiler, however I noticed that void was used by visual studio (not sure if this is ok). Is it possible for a function object to auto deduce types, why or why not? If not is there some workaround, as types can get long to type?


Solution

  • This is a feature that was introduced by c++14 (which is supported by g++5.1 and can be activated by passing the -std=c++14 flag).

    If you don't specify a type, the compiler takes the default one (void) for which there exists a specialization. This specialization has a templated operator() member function for which the parameter types are then deduced by the compiler according to the iterator's value type.