C++将未知类型传递给虚函数

Avn*_*ron 17 c++ templates virtual-functions

我正在用C++编写,我想将一个未知类型(仅在运行时知道)传递给纯虚函数:

virtual void DoSomething(??? data);
Run Code Online (Sandbox Code Playgroud)

where DoSomething是派生类中纯虚函数的实现.

我打算使用模板,但因为它结果是虚函数和模板不能一起工作:C++类成员函数模板可以是虚拟的吗?

我想避免为我传递给函数的所有类使用基类(类似于C#中的对象).

提前致谢

Sto*_*ica 18

你需要类型擦除.一个例子是通用boost::any(std::any在C++ 17中).

virtual void DoSomething(boost::any const& data);
Run Code Online (Sandbox Code Playgroud)

然后每个子类都可以尝试安全 any_cast,以获得它期望的数据.

void DoSomething(boost::any const& data) {
  auto p = any_cast<std::string>(&data);

  if(p) {
    // do something with the string pointer we extracted
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您寻求的行为范围受到更多约束,您当然可以推出自己的类型擦除抽象.