Using std :: less with std :: function

7

I'm trying to meter std::function< > into a std::set< > . For this, we need a function that compares the values entered.

As std::function does not provide any comparison operator, I thought about this:

#include <functional>

template< typename... ARGS > class Test {
  using function_type = std::function< void( ARGS... ) >;
  using target_type = void ( * )( ARGS... );

  static inline bool less( const function_type &f1, const function_type &f2 ) noexcept {
    std::less< target_type > l;
    return l( f1.target< target_type >( ), f2.target< target_type >( ) );
  }
};

Test< int, int > test;

When trying to compile

  

g ++ -std = c ++ 11 -Wall -Wextra -pedantic -c test.cpp

I get a pretty error list:

  

In static member function less( ... ) :
  error: expected primary-expresion before >
  error: expected primary-expresion before )
  error: expected primary-expresion before >
  error: expected primary-expresion before )

Note: The code is the minimum reproducible. I have kept what I think is important

  • What am I doing wrong?

  • How do I solve it?

asked by Trauma 08.01.2018 в 15:34
source

1 answer

10

The parser becomes a mess when interpreting the template function of an object whose type depends on template parameters, to disambiguate the interpretation of the analyzer it is necessary to add the keyword template :

template< typename... ARGS > class Test {
  using function_type = std::function< void( ARGS... ) >;
  using target_type = void ( * )( ARGS... );

  static inline bool less( const function_type &f1, const function_type &f2 ) noexcept {
    std::less< target_type > l;
    return l( f1.template target< target_type >( ), f2.template target< target_type >( ) );
//               ~~~~~~~~   son funciones plantilla!   ~~~~~~~~
  }
};

Without adding template the analyzer interprets it in another way:

//            v <-- Menor que
l( (f1.target < target_type) >( ), 
//  ~~~~~~~~~   ~~~~~~~~~~~
//   simbolo      simbolo
// ~~~~~~~~~~~~~~~~~~~~~~~~~ <-- expresión.

The analyzer finds an expression (it is not evaluated by a parser) and continues to interpret the text, seeing that after an expression " this smaller than that " one of the operands being a type ( target_type ) so that the expression is not valid and issues the error we have seen.

    
answered by 08.01.2018 / 18:20
source