【问题标题】:Inheriting member function pointers继承成员函数指针
【发布时间】:2016-06-24 19:46:19
【问题描述】:

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

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

#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如何知道如何调用添加到它的成员函数?

【问题讨论】:

  • @n.m.但是它们需要存储在某个地方吗?
  • 不涉及基类,TestSuite是。
  • 对不起,我想我不明白你在问什么。成员函数不会“存储”在任何地方,它们只是。成员函数指针存储在它们的社会化数据类型中。它们是没有任何结构的原始数据类型。
  • @kfsone 那么TestSuite 怎么知道如何调用这些函数呢?它们必须与StudentTestCase 类型的对象链接,对吗?
  • @Downvoter 为什么投反对票?

标签: c++ pointers c++11 function-pointers member-function-pointers


【解决方案1】:

我的猜测是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中,派生类被实例化,并且这种类型的对象被动态分配。存储的是指向非模板基类的指针。

【讨论】:

  • @Curious :-) 当我第一次看到这种技术时(在某些序列化库中),我非常高兴。
  • 但是在代码中,new 运算符在没有模板参数的情况下被调用。那么这真的有效吗?
  • 哦不,可能,该函数已添加到 TestCaller 类中。谢谢!
猜你喜欢
  • 2012-04-12
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多