Deducing类型,当使用成员函数指针作为模板参数时 [英] Deducing type, when using member function pointer as template argument

查看:77
本文介绍了Deducing类型,当使用成员函数指针作为模板参数时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想有成员函数作为模板参数时,是否有一种方法来to化它,而不提供 Caller 类型?

  struct Foo 
{
template< typename Caller,void(Caller :: * Func) int)>
void call(Caller * c){(c-> * Func)(6); }
};

struct Bar
{
void start()
{
Foo f;
f.call< Bar,& Bar :: printNumber>(this);
^^^^
}

void printNumber(int i){std :: cout<一世; }
};

int main()
{
Bar b;
b.start();
return 0;
}




  template< void(Caller :: * Func)(int),typename Caller> 
void call(Caller * c){(c-> * Func)(6); }

并调用

  f.call<& Bar :: printNumber>(this); 

我得到 Caller不是类...

解决方案

不,不是你想要的。 如果


  1. ,则可以推导出调用者参数,而不是模板参数。例如:

     模板< class Caller> 
    void call(Caller * c,void(Caller :: * Func)(int)){(c-> * Func)(6); }


  2. 例如,您可以使调用看起来像这样:

      f.arg(this).call< printNumber>(); 

    调用函数看起来类似于:

     模板< class Arg> 
    struct Binder
    {
    template< void(Arg :: * Func)(int)>
    void operator()()const {
    ...
    }
    };

    arg 函数很容易写(在您的情况下,它会返回 Binder< Bar> ,其中 Bar 是从





When I want to have member function as template argument, is there a way to templetize it without providing Caller type?

struct Foo
{
    template <typename Caller, void (Caller::*Func)(int)>
    void call(Caller * c) { (c->*Func)(6); }
};

struct Bar
{
    void start() 
    {
        Foo f;
        f.call<Bar, &Bar::printNumber>(this);
               ^^^^  
    }

    void printNumber(int i) { std::cout << i; }
};

int main ()
{
    Bar b;
    b.start();
    return 0;
}

when I try

template <void (Caller::*Func)(int), typename Caller>
void call(Caller * c) { (c->*Func)(6); }

and call it like

f.call<&Bar::printNumber>(this);

I am getting Caller is not class... error.

So, is there a way to let compiler deduce the Caller type?

解决方案

No, not as you want it. Caller could be deduced if

  1. the pointer to member function were an parameter, not a template parameter. Eg:

    template <class Caller>
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
    

  2. it was known beforehand. For example, you could make the call look like this:

    f.arg(this).call<&Bar::printNumber>();
    

    The call function would look similar to this:

    template <class Arg>
    struct Binder
    {
      template<void (Arg::*Func)(int)>
      void operator()() const {
        ...
      }
    };
    

    The arg function would be easy to write (in your case it would return Binder<Bar>, where Bar is deduced from this).

    Not very convenient, IMHO.

这篇关于Deducing类型,当使用成员函数指针作为模板参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆