我很难理解为什么我的模板层次结构不会传递比一层更深的构造函数参数。模板层次结构构造函数参数
到目前为止,我读过它可能与名称空间或模板构造函数未命名有关。我通过范围指令将构造函数参数传递给基类的各种尝试都失败了。
// test.cc
#include <string>
// Base class, obviously.
template <typename T>
class Base {
public:
Base(const T& t) : _t(t) {}
virtual ~Base() { }
virtual T getVal() const { return _t; }
private:
T _t;
};
// First derivation. This works, although it is explicit.
class DerivedOne : public virtual Base<std::string>
{
public:
DerivedOne(const std::string& path) : Base<std::string>(path) {}
virtual ~DerivedOne() {}
};
// Second derivation. Constructor fails to compile unless I explicitly
// pass the 'path' argument to Base in the initializer list or create a
// default constructor for Base (which, of course, leaves Base::_t
// uninitialized).
class DerivedTwo : public virtual DerivedOne
{
public:
DerivedTwo(const std::string& path) : DerivedOne(path) {}
// This works
// DerivedTwo(const std::string& path) : DerivedOne(path), Base(path) {}
virtual ~DerivedTwo() {}
};
int main()
{
return 0;
}
编译器会抱怨:
test.cc: In constructor ‘DerivedTwo::DerivedTwo(const string&)’:
test.cc:31:58: error: no matching function for call to ‘Base<std::__cxx11::basic_string<char> >::Base()’
DerivedTwo(const std::string& path) : DerivedOne(path) {}
^
test.cc:7:5: note: candidate: Base<T>::Base(const T&) [with T = std::__cxx11::basic_string<char>]
Base(const T& t) : _t(t) {}
^
test.cc:7:5: note: candidate expects 1 argument, 0 provided
test.cc:5:7: note: candidate: Base<std::__cxx11::basic_string<char> >::Base(const Base<std::__cxx11::basic_string<char> >&)
class Base {
^
test.cc:5:7: note: candidate expects 1 argument, 0 provided
为什么我需要声明一个默认的构造函数时,它似乎是参数的构造函数应该叫什么名字?为什么我必须显式地将DerivedTwo的参数传递给Base,因为我已将它传递给DerivedOne(谁应该将它传递给Base)?
有没有办法避免这种重复?这是否意味着当派生类初始化程序列表中的堆上分配了基本模板构造函数参数时,我不能使用初始化程序列表?
这就是虚拟继承的工作原理。你是否真的想在'class DerivedOne:public virtual Base'和'class DerivedTwo:public virtual DerivedOne'中使用'virtual'?请注意,不需要使用虚拟功能。 –
NathanOliver
在真正的单词应用程序中,需要虚拟功能。我仍然不明白为什么它是必要的,也许我需要重新研究虚拟继承。 – vincent
只有当您通过多重继承多次继承共同祖先时才需要虚拟继承。 – cababunga