gpt4 book ai didi

c++ - 无法从派生类调用 Base 模板化类的构造函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:03:17 25 4
gpt4 key购买 nike

我有这样的层次结构:

#include <boost/shared_ptr.hpp>
//base cache
template <typename KEY, typename VAL> class Cache;
//derived from base to implement LRU
template <typename KEY, typename VAL> class LRU_Cache :public Cache<KEY,VAL>{};
//specialize the above class in order to accept shared_ptr only
template <typename K, typename VAL>
class LRU_Cache<K, boost::shared_ptr<VAL> >{
public:
LRU_Cache(size_t capacity)
{
assert(capacity != 0);
}
//....
};

//so far so good

//extend the LRU
template<typename K, typename V>
class Extended_LRU_Cache : public LRU_Cache<K,V >
{
public:
Extended_LRU_Cache(size_t capacity)
:LRU_Cache(capacity)// <-- this is where the error comes from
{
assert(capacity != 0);
}
};

错误说:

template-1.cpp: In constructor ‘Extended_LRU_Cache<K, V>::Extended_LRU_Cache(size_t)’:
template-1.cpp:18:38: error: class ‘Extended_LRU_Cache<K, V>’ does not have any field named ‘LRU_Cache’
Extended_LRU_Cache(size_t capacity):LRU_Cache(capacity)

你能帮我找到丢失的部分吗?

谢谢

最佳答案

需要指定基类型的模板参数:

Extended_LRU_Cache(size_t capacity)
:LRU_Cache<K, V>(capacity)
{
assert(capacity != 0);
}

因为您不提供它们,所以编译器不会将您尝试调用基本构造函数的连接建立起来,因为您不是从名为 LRU_Cache 的类型派生的,所以看起来对于名称为 LRU_Cache 的字段进行初始化。现在您收到此特定错误消息的原因应该很明显了。

模板参数是必需的,因为您可以使用不同的模板参数从相同的模板类型派生两次,然后基本构造函数调用将是不明确的:

template <typename T>
class Base
{
public:
Base() { }
};

template <typename T, typename U>
class Derived : Base<T>, Base<U>
{
public:
// error: class ‘Derived<T, U>’ does not have any field named ‘Base’
// Derived() : Base() { }
// ^
// Which Base constructor are we calling here?

// But this works:
Derived() : Base<T>(), Base<U>() { }
};

关于c++ - 无法从派生类调用 Base 模板化类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498734/

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