Reputation: 5291
I have a C++ program where I am able to call non static functions by calling via object. Calling non-static function:
#include <iostream>
class ClassF {
public:
void enumerateF() {
std::cout << "f1\n";
std::cout << "f2\n";
}
};
class ClassG {
public:
void enumerateG() {
std::cout << "g1\n";
std::cout << "g2\n";
}
};
template<typename F, typename FUNC>
void do_work(FUNC g)
{
F f;
(f.*g)();
}
int main()
{
do_work<ClassF >(&ClassF::enumerateF);
do_work<ClassG >(&ClassG::enumerateG);
return 0;
}
This gives output:
f1
f2
g1
g2
How to call static function:
#include <iostream>
class ClassF {
public:
static void enumerateF() {
std::cout << "f1\n";
std::cout << "f2\n";
}
};
class ClassG {
public:
static void enumerateG() {
std::cout << "g1\n";
std::cout << "g2\n";
}
};
template<typename F, typename FUNC>
void do_work(FUNC g)
{
(F::*g)();
}
int main()
{
do_work<ClassF >(&ClassF::enumerateF);
do_work<ClassG >(&ClassG::enumerateG);
return 0;
}
This gives error:
Error C2760 syntax error: unexpected token 'identifier', expected ')'
But I don’t know how to call static functions by passing the name of the static function as parameter to a template. Please help
Upvotes: 3
Views: 2510
Reputation: 173044
You can invoke the static member function via the function poitner g
directly as
g();
Note that &ClassF::enumerateF
constructs a function pointer with type void(*)()
, which has become unrelated with the class type ClassF
. That means, you don't need the template parameter F
as the class type, which has been specified when specifying the static member function. e.g.
template<typename FUNC>
void do_work(FUNC g)
{
g();
}
and then
do_work(&ClassF::enumerateF);
do_work(&ClassG::enumerateG);
Upvotes: 4