【问题标题】:typedef the following type : Pointer to a member function Fof "any" class having a member function Ftypedef 以下类型:指向具有成员函数 F 的“任何”类的成员函数 F 的指针
【发布时间】:2014-11-12 02:10:07
【问题描述】:

我实际上是在尝试定义以下类型:X 和 Y 是类型,我想定义指向“a”类 T 的成员函数 Y F( X ) const 的指针的模板类型。

为此,我定义了以下内容:

template<typename T, typename X, typename Y>
struct GenericFunc
{
    typedef Y (T::*F) ( X ) const ;
};

现在如果

class Fct
{
    public:
        Fct( /* something */);
        double F( double ) const
        {
            // stuff...
        }
};

如果我声明

Fct thef(/* something */);
GenericFunc<Fct, double, double>::F phi ;

我想使用 thef 和 phi 来获得双精度,但我无法成功。任何想法 ?什么是 F 是 operator() ?

事实上,我可以这样做:

Fct thef(/* something */);
double (Fct::*fptr) (double) const = & Fct::F ; // or double (Fct::*fptr) (double) const = & Fct::operator() ;
double x = 3.14159 ;
double y = (thef.*fptr)(x);

但我想以泛型的方式进行,即在具有成员函数 F 的类 T、F 的参数的类型 X 和 F 的返回类型 Y 上泛型。

非常感谢

PS:我使用的是 c++

【问题讨论】:

  • " 想使用 thef 和 phi 来获得双精度,但我无法成功。" 您面临的(确切)问题是什么? “什么是 F is operator() ?” 我不太明白你在问什么。 operator() 成员函数就像任何其他成员函数一样,只是有一个有趣的名字。
  • 其实我忘了说我想用double (Fct::*fptr) (double) const = &amp; Fct::F。是的,我知道operator() 只是一个函数的名称,但是当我尝试使用或不使用operator() 时,我被智能感知的不同行为误导了。

标签: c++ templates operators member-function-pointers


【解决方案1】:

这行得通:

Fct thef;
GenericFunc<Fct, double, double>::F phi = &Fct::F;
double x = (thef.*phi)(1);

Online Demo

【讨论】:

  • 非常感谢!在某个时候,我昨天尝试过这个,但其他东西引发了智能感知错误......
猜你喜欢
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2017-07-27
  • 2013-06-06
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
相关资源
最近更新 更多