我有这样的层次结构:
#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)
你可以帮我找到缺失的部分吗?
感谢
答案 0 :(得分:2)
调用基础构造函数时,需要父级的完整定义(即使用模板参数):
Extended_LRU_Cache(size_t capacity)
:LRU_Cache<K,V>(capacity)
{
assert(capacity != 0);
}
答案 1 :(得分:2)
您需要指定基本类型的模板参数:
Extended_LRU_Cache(size_t capacity)
:LRU_Cache<K, V>(capacity)
{
assert(capacity != 0);
}
因为您没有提供它们,所以编译器不会建立您尝试调用基础构造函数的连接,因为您不能从名为LRU_Cache
的类型派生,所以它查找名称为LRU_Cache
的字段以进行初始化。现在应该很清楚为什么会收到这个pariticular错误消息。
模板参数是必需的,因为您可以使用不同的模板参数从相同的模板化类型派生两次,然后基础构造函数调用将是不明确的:
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>() { }
};