简体   繁体   中英

C++ Pointer to Member Function as Template Default Argument

is it possible, like this:

template< typename C,
          typename R,
          typename A,
          typename F=R (C::*)(A) >
class MemberFuncPtr { ...

Yes, it is perfectly valid.

class X {
public:
    void Y() {
    }
};

int main() {
    MemberFuncPtr<X, void, void> func;
}

Build succeeded.

Actually,it seems pretty right to me, I do not get any errors for this piece of code:

template< typename C, 
          typename R, 
          typename A, 
          typename F=R (C::*)(A) > 
class MemberFuncPtr
{
        C & Cmember;
        F f;
public:
        MemberFuncPtr(C & c, F func):Cmember(c), f(func) {}
        R DoIt(A & a)
        {
                return (Cmember.*f)(a);
        }
};
class classA
{
public:
        int toInt(double aa)
        {
                return int(aa);
        }
};
int main()
{
        classA aInstance;
        MemberFuncPtr<classA,int,double> xx(aInstance,&classA::toInt); 
        return 0;
} 

You can observe the code here .

Using typedef will make your code more user-friendly. Just typedef pointer to function, then use it as other types.

At first you can write template wrapper:

template < typename C >
class CWrapper
{
 typedef R(C::func*)(A);
 C* realC;
 Cwrapper(C* c):realC(c){}
};

then write you class this way:

template < typename C,
           typename R,
           typename F = C::func >
class MemberFuncPtr{...

then make MemberFuncPtr< CWrapper <C>, R> memFuncPtr;

Corrected Sad_man's code with some C++0x magic: http://ideone.com/rng6V (probably not gonna work for you, as not many compilers has C++0x :-|)

Works with rvalues and there is example how to achieve what you want with lambda functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM