获取没有对象的class的vtable

Obtain the vtable of a class without an object

我正在尝试实施类似于 the first described here 的系统。也就是说,(ab)使用 vtable 修改来在运行时更改对象行为。这是我在我正在处理的 C++ 项目中创建高效类型通用包装器的尝试的一部分。

示例,如果您无法访问它,请使用 memcpy()this 指针复制 vtable:

void setType( const DataType& newType )
{
    memcpy( this, &newType, sizeof(DataType) );
}

但是,我对这种方法有一个问题:我没有目标 class 的对象来从中复制 vtable,并且不想创建一个,因为某些类型的成本很高构建。

有没有一种方法可以在没有 class 的对象的情况下访问将被放置到给定 class 的对象中的 vtable?

如果它具有一定的可移植性,那将是更好的选择,但我基本上已经接受了它是特定于编译器的;因此,如果没有其他选择,仅 GCC/G++ 方法是可以接受的。我们还假设我只关心在相当标准的操作系统和架构上构建它。

我正在使用 C++11,它应该以某种方式帮助我。

编辑:我想说清楚,我知道这种行为有多危险。我对这个想法更感兴趣,也许它在非常受控的情况下的狭窄应用比我对它作为生产软件的好主意更感兴趣,尽管我的介绍可能会暗示什么。

struct many_vtable {
  void(*dtor)(void*);
  void(*print)(void const*,std::ostream&);
};
template<class T>struct tag_t{};
template<class T>constexpr tag_t<T> tag = {};

template<class T>
many_vtable const* make_many_vtable(tag_t<T>){
  static const many_vtable retval = {
    // dtor
    [](void* p){
      reinterpret_cast<T*>(p)->~T();
    },
    // print
    [](void const*p, std::ostream& os){
      os<<*reinterpret_cast<T const*>(p);
    }
  };
  return &retval;
}
struct many {
  many_vtable const* vtable=nullptr;
  std::aligned_storage_t<100, alignof(double)> buff;
  void clear(){if(vtable) vtable->dtor(&buff);vtable=nullptr;}
  ~many(){ clear(); }
  many()=default;
  many(many const&)=delete; // not yet supported
  many& operator=(many const&)=delete; // not yet supported

  explicit operator bool()const{return vtable!=nullptr;}

  template<class T,class...Args>
  void emplace(Args&&...args){
    static_assert(alignof(T) <= alignof(double), "not enough alignment");
    static_assert(sizeof(T) <= 100, "not enough size");
    clear();
    ::new((void*)&buff) T(std::forward<Args>(args)...);
    vtable=make_many_vtable(tag<T>);
  }
  friend std::ostream& operator<<(std::ostream& os, many const&m){
    if(!m.vtable) return os;
    m.vtable->print(&m.buff, os);
    return os;
  }
};

这是一个手动虚表设计。它可以存储最多 100 个字节的任何内容,其对齐方式小于可以打印到流的双精度数。

'Erasing' 进行更多(或不同)操作很容易。比如能够copy/move再多

它不违反标准,并且与链接示例有类似的开销。

many m;
m.emplace<int>(3);
std::cout << m << '\n';
m.emplace<double>(3.14);
std::cout << m << '\n';

live example.

这是手动 vtable,因为我们基本上是手动重新实现 vtable 概念。