【发布时间】:2015-06-30 04:47:47
【问题描述】:
我有一个模板基类,它接受 N 种类型:
template <typename... Ts>
class Base{};
在该基类上使用受保护的继承时,
template <typename... Ts>
class Derived : protected Base<Ts...>{
//like so...
};
我想另外包含基类的公共构造函数:
template <typename... Ts>
class Derived : protected Base<Ts...>{
//create an alias
using Parent = Base<Ts...>;
//get all constructors as well
using Parent::Parent;
};
这行得通。
但是,为什么我必须包含 Parent 别名?
似乎没有它我无法获得构造函数。以下尝试不起作用:
template <typename... Ts>
class Derived : protected Base<Ts...>{
//get all constructors as well
using Base<Ts...>::Base<Ts...>;
};
错误:
clang++ -std=c++1z -o main v.cpp
error: expected ';' after using declaration
using Base<Ts...>::Base<Ts...>;
^
;
1 error generated.
我可以切断模板部分,它可以编译,但这似乎不正确:
template <typename... Ts>
class Derived : protected Base<Ts...>{
//get all constructors as well
using Base<Ts...>::Base;
};
我认为它不正确的原因是它似乎不适用于矢量。
无法编译:
template <typename... Ts>
class Derived : protected std::vector<Ts...>{
//get all constructors as well
using std::vector<Ts...>::std::vector;
};
但是,使用别名确实有效。
编译:
template <typename... Ts>
class Derived : protected std::vector<Ts...>{
//create an alias
using Parent = std::vector<Ts...>;
//get all constructors as well
using Parent::Parent;
};
问题:
我是否必须使用别名来获得相同的功能,或者有没有办法在不为基本类型创建新名称的情况下内联它?
【问题讨论】:
-
std::vector<Ts...>::std::vector不应该在 using 语句中工作。 -
@CoffeeandCode 对,它不适用于矢量。虽然它可以编译为其他类型,但我怀疑它与使用 Alias::Alias 不同。
-
不,我的意思是应该是
namespace::type::type而不是namespace::type::namespace::type -
哦,我明白了。是的,现在排除命名空间给了我与以前相同的错误(没有向量的示例,其中 clang 期望冒号早于它得到一个)。至少现在编译器错误是一致的。
-
构造函数是 not
Base<Ts...>因为构造函数没有模板化。using Base<Ts...>::Base;是正确的写法。
标签: c++ templates inheritance variadic-templates c++14