c++ - 使用模板生成 const 和 non-const 相同的方法?

标签 c++

是否可以定义一个 interface比如:

class IFoo
{
  virtual void foo(const X &x) const = 0;
  virtual void foo(X &x) = 0;
};

并同时定义 foo子类中的方法 C使用可以实例化两次的模板,一次用于类型参数 <const X>一次是 <X> ?例如:

class C : public IFoo
{
  template<typename T>
  void foo(T &t) {...}
};

// instantiate void C::foo(X &x)
//         and void C::foo(const X &x) const ???

最佳答案

模板函数不能是虚函数,因此即使您能够根据模板参数应用 const-ness,您也不会覆盖虚函数。例如,以下代码无法在 g++ (4.8.5) 上编译:error: templates may not be ‘virtual’

#include <iostream>

class IFoo
{
  virtual void foo(int &x) = 0;
};

class C : public IFoo
{
  template<typename T>
  virtual void foo(T &t) override {
    std::cout << "foo" << std::endl;
  }
};

int main() {
  C c;
  c.foo(1);
  return 0;
}

关于c++ - 使用模板生成 const 和 non-const 相同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390706/

相关文章:

c++ - 为什么确定友元声明是否是其命名空间中的第一个如此重要?

c++ - QML 如何动态访问 ListView 项

python - 使用 PyArg_ParseTuple 的 C++ 和 Python 3 内存泄漏

c++ - 在不使用定义的情况下缩短调用/名称

c++ - 默认参数 : can only the last argument(s) be left?

c++ - 使用非虚拟接口(interface)沿模板类向下转换

c++ - 如何以任何 CSV、C、Python、MatLab、NumPy 样式格式打印 cv::Mat

c++ - 如何将右值作为引用参数传递给函数

c++ - 将 int 转换为 char 数组的最佳方法

c++ - SFML - 从纹理加载后 Sprite 为空白