1

I am trying to call

template <typename FUNC> int execute ( FUNC ) { int a { 5 }; int b { 8 }; return FUNC ( a, b ); } 

with the following line:

std::cout << execute ( [] ( int a, int b ){ return a + b; }) << std::endl; 

with the following error:

error C2661: 'main::<lambda_5994edd6ba73caf12c83e036d510d0d8>::<lambda_5994edd6ba73caf12c83e036d510d0d8>': Keine überladene Funktion akzeptiert 2 Argumente 

So the question is what am i doing wrong? The error is German but it basically just says that the function doesn't take 2 parameters which it clearly should do

1
  • FUNC is not valid argument to function in this context. Every argument(again, in this context) must consist of type name, and variable name(in case you want to refer to it, which you want 99% of time). Just make your function accept std::function<void(int, int)> and you are good to go Commented Oct 17, 2014 at 14:56

2 Answers 2

6

No, that is not how you should call that function. You didn't specify the argument's name. What you tried to do, is to use the type as a function.

Corrected template function is :

template <typename FUNC> int execute ( FUNC f ) { int a { 5 }; int b { 8 }; return f( a, b ); } 
Sign up to request clarification or add additional context in comments.

Comments

2

You're not actually calling the function... you're constructing an object of type FUNC and returning it, and FUNC is not convertible to int. What you meant is:

template <typename FUNC> int execute (FUNC&& f) { int a { 5 }; int b { 8 }; return f( a, b ); } 

Or alternatively (originally wrote "better" but that is bad word choice):

int execute(std::function<int(int, int)> f) { int a { 5 }; int b { 8 }; return f( a, b ); } 

7 Comments

Why do you consider std::function better than the template parameter? std::function has a construction overhead and a type erasure overhead.
Better is probably the wrong word. There are cases where type erasure is a good thing, and I wanted to just show that that was a possible solution.
should be return std::forward<FUNC>(f)( a, b ); in first example
@PiotrS. You're right of course, technically. But I wonder whether anyone will ever create a practical class with an operator() &&. Or do you know of a use-case?
@Angew consider following use case coliru.stacked-crooked.com/a/30a70730dc7e85dc , if you ever start treating forwarding-reference as a regular lvalue then you are asking for troubles
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.