In some languages (PHP and JavaScript come to mind), I can use a variable as a function. For example:
PHP: Class::$var_function();
Is it possible to this in C++ in a way that doesn't require a switch or if statement?
In some languages (PHP and JavaScript come to mind), I can use a variable as a function. For example:
PHP: Class::$var_function();
Is it possible to this in C++ in a way that doesn't require a switch or if statement?
Yes. Such a variable is called a function pointer (for nonmember or static member functions) or a pointer-to-member-function (for nonstatic member functions).
Alternatively, Boost, C++ TR1, and C++11 all provide a polymorphic function
wrapper, which is basically an uber-flexible, general purpose, generic function pointer type.
This is what pointers to functions allow you to do.
int max(int v1, int v2) { return (v1 > v2) ? v1 : v2; }
int min(int v1, int v2) { return (v1 < v2) ? v1 : v2; }
int add(int v1, int v2) { return v1 + v2; }
int (*function)(int, int) = add;
int x = function(1, 3); // x == 4
function = min;
int y = function(1, 3); // x == 1
Etc.
You can also get pointers to member functions in C++; the notation is somewhat different.
You may see code invoking functions via pointers to functions using the notation:
function = max;
int z = (*function)(1, 3); // x == 3
This is old fashioned, pre-standard C. But it makes it clear that a pointer-to-function is being used (so I still like it and often use it).
James' answer is probably the best. But, if you're using a c++11 compatible compiler, you can alternately use std::function
For example:
#include <functional>
#include <iostream>
typedef std::function<void(int a)> callback_t;
class A {
public:
void fn(int a) { std::cout << a << std::endl; }
};
void fn2(int b) { std::cout << a << std::endl; }
int main() {
A a;
callback_t c = std::bind(&A::fn, a, std::placeholders::_1);
c(1);
c = fn2;
c(2);
return 0;
}
And a boost version (I've never used this so it may be wrong):
#include <boost/function.hpp>
#include <iostream>
typedef boost::function<void(int a)> callback_t;
class A {
public:
void fn(int a) { std::cout << a << std::endl; }
};
void fn2(int b) { std::cout << a << std::endl; }
int main() {
A a;
callback_t c = boost::bind(&A::fn, a, boost::placeholders::_1);
c(1);
c = fn2;
c(2);
return 0;
}
In addition to the other answers, you can make objects of any user-defined type act like a function (or even like a set of overloaded functions) by defining the function call operator:
class MyClass
{
public:
MyClass(): member(42) {};
void operator()(int i) { std::cout << (member=i) << '\n'; }
void operator()() { std::cout << member++ << '\n'; }
private:
int member;
};
int main()
{
MyClass foo;
foo(); // prints 42
foo(); // prints 43
foo(23); // prints 23
foo(); // prints 24
}