Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用成员函数指针作为模板参数时推断类型_C++_Templates - Fatal编程技术网

C++ 使用成员函数指针作为模板参数时推断类型

C++ 使用成员函数指针作为模板参数时推断类型,c++,templates,C++,Templates,当我想让成员函数作为模板参数时,有没有一种方法可以在不提供调用者类型的情况下将其模板化 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, &a

当我想让成员函数作为模板参数时,有没有一种方法可以在不提供
调用者
类型的情况下将其模板化

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;
}
structfoo
{
模板
无效调用(调用方*c){(c->*Func)(6);}
};
结构条
{
void start()
{
福福;
f、 叫(这个);
^^^^  
}
void printNumber(inti){std::cout*Func)(6);}
就这样说吧

f.call<&Bar::printNumber>(this);
f.调用(this);
我收到
调用方不是类…
错误


那么,有没有一种方法可以让编译器推断调用者类型?

没有,不是您想要的。如果

  • 指向成员函数的指针是一个参数,而不是模板参数。例如:

    template <class Caller>
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
    
    arg
    函数将易于编写(在您的情况下,它将返回
    Binder
    ,其中
    Bar
    是从
    这个
    推导出来的)

    不太方便


  • 非常感谢!我甚至不知道为什么我尝试将其模板化而不是常规参数:)再次感谢
    template <class Caller>
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
    
    f.arg(this).call<&Bar::printNumber>();
    
    template <class Arg>
    struct Binder
    {
      template<void (Arg::*Func)(int)>
      void operator()() const {
        ...
      }
    };