Reputation: 33
I have a function template:
template < typename A, typename B, typename xClass, typename D>
void foo(A& a, B& (xClass::*fooPtr)(D& d));
{
//some code
}
I have some classes, which I want to use later as an xClass in my function. But their member functions have different const-qualifiers:
const out_t& Class1::foo1(in_t) const // (1)
out_t& Class1::foo1(in_t) // (2) just non-const version of foo1(), making the same actions
out_t& Class2::foo2(in_t) const // (3)
Now, if I use
... B& (xClass::*fooPtr)(D& d) ...
in function template, only pointer to (2) member function makes foo() work, others cause "incompatible cv-qualifiers" error. Howewer, adding "const" qualifier:
... B& (xClass::*fooPtr)(D& d) const ...
makes (3) working, but now (2) (and (1) also) causes error.
Is there a simple way to make function foo() to "do not notice" cv-qualifiers of pointers to member functions? I tried to use reinterpret_cast in order to make all necessary pointers to member functions similarly cv-qualified:
typedef B& out_t& (Class1::*fooPtr)(in_t) const;
fooPtr myPtr = reinterpret_cast<fooPtr>(&Class1::foo1);
but it failed.
Upvotes: 1
Views: 466
Reputation: 64308
One approach is to make your foo
function more general, so that it just takes a member pointer of any type:
template < typename A, typename F, typename xClass>
void foo(A& a, F xClass::*fooPtr)
{
//some code
}
This means that foo
will accept pointers to data members or member functions that have signatures other than what you want, but it usually isn't that big of a problem. If you pass the wrong type of member, you'll typically just get a compilation error because the member function can't be called the way you are calling it. If you want to restrict it more, you can use SFINAE tricks.
Upvotes: 1