0

I'm trying to compare the function pointer stored in two std::function objects, declared as std::function<void(Args...)> where Args... is a class template parameter. I intended to do this by comparing the output of target(), but I'm having trouble accessing that value. What's the correct way access std::function::target()?

Below is a boiled-down version of what I've tried:

#include <functional>

template <typename... Args>
void check(std::function<void(Args...)> func)
{
  auto type = func.target<void(*)(Args...)>();
}

void m() {}

int main()
{
  auto func = std::function<void()>(m);
  check<>(func);
}

And the output from compiling with g++ -std=c++11 Demo.cpp:

Demo.cpp: In function ‘void check(std::function<void(Args ...)>)’:
Demo.cpp:6:27: error: expected primary-expression before ‘void’
    6 |   auto type = func.target<void(Args...)>();
      |                           ^~~~
Demo.cpp:6:27: error: expected ‘,’ or ‘;’ before ‘void’
Nick
  • 377
  • 5
  • 12
  • 1
    The error show different code than what's in the example, but your issue is that you need to put `template` after `func.`: `func.template target<...>()`. – 0x499602D2 Feb 19 '20 at 01:40
  • https://en.cppreference.com/w/cpp/utility/functional/function/target points out that `target` only has a value somtimes, but in this case it should have a value. It also mentions that it only exists after C++11, is your compiler set to C++11 mode? – Mooing Duck Feb 19 '20 at 01:40
  • 1
    You need to use `auto type = func.template target();`. See the linked question for more information. – Sam Varshavchik Feb 19 '20 at 01:43
  • Can't say I've come across that particular syntax combination before, very interesting. Thanks! – Nick Feb 19 '20 at 01:47

0 Answers0