【问题标题】:Calling a member function from a member function templated argument从成员函数模板参数调用成员函数
【发布时间】:2010-02-18 16:38:33
【问题描述】:

鉴于以下我无法编译的代码。

    template < typename OT, typename KT, KT (OT::* KM)() const >
    class X
    {
    public:
        KT mfn( const OT & obj )
        {
            return obj.*(KM)();    // Error here.
        }
    };

    class O
    {
    public:
        int func() const
        {
            return 3;
        }
    };

    int main( int c, char *v[] )
    {
        int a = 100;

        X<  O, int, &O::func > x;

        O o;

        std::cout << x.mfn( o ) << std::endl;
}

我收到以下错误消息

error: must use '.*' or '->*' to call pointer-to-member function in '&O::func (...)'

我以为我在使用 .* 但我显然有问题。

如何调用成员函数?

我试过了

return obj.*(template KM)();
return obj.*template (KM)();
return obj.template *(KM)();

这些都不起作用。

【问题讨论】:

  • 函数指针真是可怕的野兽:(
  • 请注意,template 仅用于依赖模板,O::func 不是模板函数。

标签: c++ templates function-pointers member-function-pointers pointer-to-member


【解决方案1】:

正确的语法是

return (obj.*KM)();

【讨论】:

  • 谢谢 Gareth.. 我是正式的布偶 :) 那是我唯一没有尝试过的。
  • 提醒一下,如果没有将要作用的对象,请考虑指向函数的指针不完整(毕竟需要this)。如果你从函子的角度来看,它更有意义,至少我就是这样尝试记住语法的......当我不能时,我只是谷歌C++ pointer to function,这是总是马上出现的链接:@987654321 @ :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
相关资源
最近更新 更多