Hakkerwell Hakkerwell
Hakkerwell Hakkerwell

Reputation: 61

Passing function into function with std::function and template argument

I am trying to pass a pointer to the predicate function into the Foo and Bar functions. The Bar function works correctly, but the Foo function raises a compile-time error:

error: no matching function for call to Foo<int>(bool (&)(int))

Why does the compiler raise an error? Is there any difference between Foo's and Bar's template arguments types after Args' unpacking?

#include <functional>

bool predicate(int a) {
    return (a > 5);
}

// sizeof...(Args) == 1 and I suppose it is int
template<typename... Args>
void Foo(std::function<bool(Args...)> predicate) {
    // clang: note: candidate template ignored:
    //        could not match 'function<bool (int, type-parameter-0-0...)>' 
    //        against 'bool (*)(int)'
}

template<typename Args>
void Bar(std::function<bool(Args)> predicate) {

}

int main(int argc, char const *argv[]) {
    // gcc: error: no matching function for call to
    //      'Foo<int>(bool (&)(int))'
    Foo<int>(predicate);
    Bar<int>(predicate);
    
    return 0;
}

See Compiler Explorer for a live example.

I also tried to change the Foo function a little and it works somehow:

template<typename... Args>
void Foo(bool(*predicate)(Args...)) {
  std::function<bool(Args...)> func(predicate);
}

I want to have std::function type argument in the Foo function, but I don't know how to do it

Upvotes: 6

Views: 384

Answers (1)

Waqar
Waqar

Reputation: 9376

The error is because the exact type of std::function is not same as predicate. To get around this, you can explicitly call the constructor of std::function:

int main() {
    Foo<int>( std::function<bool(int){predicate} );
    //OR
    Foo<int>( {predicate} );
    return 0;
}

Upvotes: 1

Related Questions