gpt4 book ai didi

c++ - 无法实例化抽象类 : Why is the template parameter (reference) causing this?

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:49 25 4
gpt4 key购买 nike

我在处理某些代码时遇到了问题。

'Bar' : cannot instantiate abstract class

我(终于)能够用少量代码重现错误。

struct SomeStruct
{
// ******
};

template <typename TIN, typename TOUT, typename TINDEX>
struct IFoo
{
public:
virtual void add(const TIN item) = 0; // <-- BAD
//virtual void add(const TOUT& item) = 0; // <-- GOOD

// ******
};

template <typename TVALUE, typename TINDEX>
struct Bar : IFoo<TVALUE &, TVALUE, TINDEX>
{

public:

void add(const TVALUE& item)
{
// ******
}

// ******
};

int main(int argc, char *argv[])
{
SomeStruct someStruct;
Bar<SomeStruct, int> bar = Bar<SomeStruct, int>();
bar.add(someStruct);

// ******
}

谁能告诉我为什么使用带有模板参数的引用会导致这种情况?

最佳答案

这里的问题是,当您编写 const TIN 并且 TIN 是引用类型时,const 适用于 引用 而不是值类型。

这就是为什么您看到 const TINconst TOUT& 有不同的行为,即使您认为它们应该相同。

解决这个问题的一个简单方法是将 const 添加到 IFoo 实例化中的值类型:

struct Bar : IFoo<const TVALUE &, TVALUE, TINDEX>
// here ^^^^

关于c++ - 无法实例化抽象类 : Why is the template parameter (reference) causing this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895106/

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