是否可以定义一个 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/