2

What is the fastest and shortest way to pass a function as parameter of another function without using other libraries other than the std one in just one line?

I mean let's say we have a function forloop(int x, *) {...} that run a for loop from 0 to x running the * function; the function call should be something like: forloop(3, **() { std::cout "Hi!"; });.

PS: * and ** are just placeholders for the function-by-argument type and the way to pass the function as argument.

Shoe
  • 74,840
  • 36
  • 166
  • 272

3 Answers3

3

C++11 provides anonymous functions:

forloop(3, []{ std::cout "Hi!"; });

Example:

#include <iostream>
#include <functional>

 void forloop(int times, std::function<void()> f) {
     for(int i = 0; i < times; i++) {
         f();
     }
 }

int main() {
    forloop(3, [] () { std::cout << "Hello world"; });
}
phant0m
  • 16,595
  • 5
  • 50
  • 82
  • What would the type of `*` be? – Shoe Nov 24 '12 at 21:17
  • @Jeffrey The type is `std::function` - include – phant0m Nov 24 '12 at 21:20
  • @phant0m: No, it will be **convertible** to `std::function`. Its exact type is unspecified but can be obtained by `decltype` – Armen Tsirunyan Nov 24 '12 at 21:22
  • @ArmenTsirunyan I did when testing, I only included it because he asked about being able to pass it. – phant0m Nov 24 '12 at 21:23
  • I'm seriously confused right now. I've tried your way (std::function) but with no success. Can you please make an example of the prototype for `forloop` if I'm going to use it like your first example? – Shoe Nov 24 '12 at 21:27
  • @Jeffrey: std::function and lambdas is part of C++11 . Does your compiler support C++11? If not, you could try boost::function and boost::lambda – Armen Tsirunyan Nov 24 '12 at 21:30
  • @ArmenTsirunyan, I have gcc 4.2.1. How do I check what version of C++ is it supporting? – Shoe Nov 24 '12 at 21:33
  • @Jeffrey [**You need GCC 4.3 or later**](http://gcc.gnu.org/projects/cxx0x.html). – phant0m Nov 24 '12 at 21:34
0

Try "pointers to member functions" if your function is a member of any class.

Furkan
  • 683
  • 2
  • 10
  • 26
0

You are looking at several options.

  1. function pointers, the C style way
  2. std::function which is part of C++ TR1 and C++11
  3. use functors and std::ptr_fun to adapt your function

The syntax you are showing is only going to work with C++11. Earlier C++ versions don't offer the possibility to define an anonymous function.

pmr
  • 58,701
  • 10
  • 113
  • 156
  • I'm not using any syntax, I just invented it. What would `*` and `**` replaced with (if I have C++11)? – Shoe Nov 24 '12 at 21:25