gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:20 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com