Reputation: 33
I have this problem:
template <void (*F)(int)> struct FunctionWrapper // This compiles and works
{
static void call_it()
{
F(0);
}
};
class MyClass
{
public:
static void callMe(int k)
{
}
};
template <void (MyClass::*F)(int)> struct FunctionWrapper // Error - F incompatible with declaration
{
static void call_it()
{
MyClass::F(0);
}
};
Why I can use a function pointer (compile time constant) but not a class-member (even static) one?
Upvotes: 2
Views: 94
Reputation: 126432
Why I can use a function pointer (compile time constant) but not a class-member (even static) one?
You can use a pointer to a static function as a regular function pointer. For instance, the following works:
template <void (*F)(int)> struct FunctionWrapper
{
static void call_it()
{
F(0);
}
};
class MyClass
{
public:
static void callMe(int k)
{
}
};
int main()
{
FunctionWrapper<&MyClass::callMe> obj;
obj.call_it();
}
Concerning your attempt, this is what Paragraph 14.1/4 of the C++11 Standard mandates:
A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
— integral or enumeration type,
— pointer to object or pointer to function,
— lvalue reference to object or lvalue reference to function,
— pointer to member,
— std::nullptr_t.
A pointer to member function (even if static
) is not an option for non-type template arguments.
Upvotes: 0
Reputation: 4207
A static function has the same type signature as a normal function; it is not really a member function.
Upvotes: 2