C++ Pointer to Member Function as Template Default

2019-07-15 15:03发布

is it possible, like this:

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

5条回答
Anthone
2楼-- · 2019-07-15 15:38

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-15 15:46

Yes, it is perfectly valid.

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

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

Build succeeded.

查看更多
Ridiculous、
4楼-- · 2019-07-15 15:49

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.

查看更多
仙女界的扛把子
5楼-- · 2019-07-15 15:55

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;

查看更多
劫难
6楼-- · 2019-07-15 15:59

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

查看更多
登录 后发表回答