c++ - 如何从父模板函数访问子成员?

标签 c++ c++11 templates type-conversion dynamic-cast

#include <iostream>
#include <functional>

using namespace std;

class Child;

class Parent {
    public:
    template <class Function, class... Args>
    void f(Function&& f, Args&&... args)
    {
        Child *c = dynamic_cast<Child*>(this);
        cout << c->n;
    }
};

class Child : public Parent {

public:
    int n = 0;
};

int main()
{
    Parent *p = new Child();
    cout << "abc";
    return 0;
}

该代码旨在从父类的模板成员函数访问子类的成员。我想这样做是因为模板成员函数不能是虚拟的。我得到的错误是:“'Child' 是一个不完整的类型”。我该如何进行这项工作?

最佳答案

可以将f的定义和声明分开,将定义移到类Child的定义之后。例如

class Child;

class Parent {
public:
    virtual ~Parent() = default;          // must be polymorphic type
    template <class Function, class... Args>
    void f(Function&& f, Args&&... args); // the declaration
};

class Child : public Parent {
public:
    int n = 0;
};

// the definition
template <class Function, class... Args>
void Parent::f(Function&& f, Args&&... args)
{
    Child *c = dynamic_cast<Child*>(this);
    if (c != nullptr)                     // check the result of conversion
        cout << c->n;
}

注意

  1. 基类 Parent 必须是 polymorphic type使用dynamic_cast ;即它必须至少有一个 virtual 函数。
  2. 你最好在使用前检查dynamic_cast的结果。

关于c++ - 如何从父模板函数访问子成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437006/

相关文章:

c++ - 如何使用 Linux 中的套接字层在 C++ 上编写 .wav 文件?

c++ - 不能使用 CV_32UC1

c++ - 暂停 std::thread 直到函数完成

c++ - C++ 容器的 decltype、通用引用和转发

javascript - 如何在 Handlebars 模板中插入 JavaScript 代码?

c++ - 如果 std::function 捕获了 unique_ptr,如何复制它?

c++ - 我将如何着手将天空盒应用于世界,openGL C++

c++ - 同时支持C++98和C++11

c++ - 为什么通过引用传递从 std::function 派生的对象会使程序崩溃?

c++ - 偏序可变参数模板函数 clang