继承成员函数指针

Inheriting member function pointers

本文关键字:指针 函数 成员 继承      更新时间:2023-10-16

我在网上看到了这段代码,我想知道它是如何实现的。 由于成员函数指针不能分配给基类的成员函数指针,我很好奇派生类的成员函数的指针存储在哪里以及如何存储。

这是带有测试声明的头文件

#ifndef TestStudent_h
#define TestStudent_h
#include <iostream>
#include <string>
// Note 1
#include "TestCase.h"
#include "TestSuite.h"
#include "TestCaller.h"
#include "TestRunner.h"
#include "Student.h"
class StudentTestCase : public TestCase { // Note 2 
public:
  // constructor - Note 3
  StudentTestCase(std::string name) : TestCase(name) {}
  // method to test the constructor
  void testConstructor();
  // method to test the assigning and retrieval of grades
  void testAssignAndRetrieveGrades();
  // method to create a suite of tests
  static Test *suite ();
};
#endif

这是将成员函数添加到某种列表中的函数的实现

// method to create a suite of tests - Note 7
Test *StudentTestCase::suite () {
  TestSuite *testSuite = new TestSuite ("StudentTestCase");
  // add the tests
  testSuite->addTest (new TestCaller  
      ("testConstructor", &StudentTestCase::testConstructor));
  testSuite->addTest (new TestCaller  
      ("testAssignAndRetrieveGrades", 
       &StudentTestCase::testAssignAndRetrieveGrades));
  return testSuite;
}

我想知道成员函数存储在什么数据类型中,因为它们不能存储在基类已知的任何函数指针类型中。 此外,存储它们的位置必须知道定义这些对象的类的类型,因为调用这些对象的任何实体都需要将这些函数与该类型的对象"链接"起来,对吗? 特别是在此函数中,TestCaller如何知道如何调用添加到其中的成员函数?

我的猜测是TestCaller有一个看起来像

template<class Callee>
TestCaller(
    const std::string &description, 
    void (Callee::*test_method)());

请注意:

  1. 在此构造函数的主体中(即,当它被实例化时),Callee的类型是已知的。

  2. TestCaller本身必须以一种不"知道"Callee的方式存储test_method,因为它本身不是由Callee参数化的模板类(事实上,可能不止一个Callee)。

所以这是类型擦除的经典案例。有许多库可以做到这一点(例如,boost::TypeErasureboost::any)。

这个想法是TestCaller存储(可能间接)指向非模板基类的指针。存在派生类的模板化版本。在此模板化 ctor 中,将实例化派生类,并动态分配此类型的对象。但是,存储的内容是指向非模板基类的指针。