c++ - 使用模板调用类的函数

标签 c++ templates inheritance methods

我可能在这里要求一些荒谬的东西(我是 c++ 的新手),但我仍然想尝试一下。我试图在接收它的对象的函数中访问类的方法,但与此同时,我想以某种方式不必指定是哪个类,这就是我使用模板的原因。这听起来非常愚蠢,但无论如何,这就是代码:

class Dog;

class Animals{
public:
// initializes all protected variables
Animals(string fam, string gen, string espec, string subespec);
~Animals();

template <class A>
void Eat(A &);

protected:
    string family;
    string genre;
    string especies;
    string subespecies;
};

template <class A>
void Animals::Eat(A &obj)
{
    // this is where I don't know what I could do.
    std::cout << obj.methodOfA();
}

/---

int main()
{
    Dog *myDog = new Dog;
    myDog->Eat(myDog);

    //supposing I had class "Cats"
    Cat *myCat = new Cat;
    myCat->Eat(myCat);
}

这可能非常愚蠢,所以请随时指出我对答案的愚蠢...如果有人回答过这个问题。 我想要这个是因为我将有许多派生自 Animals 类的类,并且独立于这些类中的哪些,我希望它们能够正确使用此方法。

谢谢。

最佳答案

解决问题的一种方法是将要执行的函数作为第二个参数传递。然后您可以使用 operator.*operator->* 调用该函数。

这看起来像这样:

class Animals {
public:
// initializes all protected variables
Animals(std::string fam, std::string gen, std::string espec, std::string subespec);
~Animals();

template <class A, class Fun>
void Eat(A *&, Fun);

protected:
    std::string family;
    std::string genre;
    std::string especies;
    std::string subespecies;
};

template <class A, class Fun>
void Animals::Eat(A *& obj, Fun function)
{
    std::cout << ((obj->*function)()).c_str();
}


class Dog : public Animals {
public:
    std::string TestFunction() {
        return std::string("I am a dog");
    }
};


int main() {

    Dog *myDog = new Dog;
    myDog->Eat(myDog, &Dog::TestFunction);

    //...
}

这个程序的输出是:

I am a dog

澄清这一行:

((obj->*function)())

您首先将operator->* 应用于obj 并将成员函数function 的地址传递给它。请注意,您必须在该语句两边加上括号。之后调用它。(())。

如果对上面提供的代码有任何疑问,请随时提问。

问候,

飞鸟

关于c++ - 使用模板调用类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191596/

相关文章:

c++ - Visual Studio C++ 6.0 是否有线程安全队列类?

c++ - 来自 "Overload"杂志的奇怪收据

c++ - 是否可以在 constexpr 中使用 std::string ?

Hibernate 继承 - 引用用 @MappedSuperclass 注释的实体

c++ - 扩展具有私有(private)构造函数和析构函数的单例类会给出编译时警告

c# - 继承和基础构造函数

c++ - 寻找最佳颜色匹配 - 如果没有可用的颜色阴影则拒绝

带有模板访问器的 Qt Q_PROPERTY

在 T1 和 T2 之间选择的 C++ 类型特征

c++ - 未调用模板参数的静态断言