有些时候我希望能写一个由一个参数化的类模板 可变参数模板参数包的标点列表,例如
template<typename ...lhs, int Punct, typename ...rhs>
struct tuple_pair
{
std::tuple<lhs...> _lhs;
std::tuple<rhs...> _rhs;
};
或者就此而言:
template<int ...lhs, typename Punct, int ...rhs>
struct seq_pair
{
std::integer_sequence<int,lhs...> _lhs;
std::integer_sequence<int,rhs...> _rhs;
};
这些很可能是我想要一个肮脏的 hack 的时刻,但无论如何 当然标准说我不能拥有它:§ 14.1.11:
If a template-parameter of a primary class template or alias template is a template parameter pack, it shall be the last template-parameter.
我不明白为什么会这样。在我看来,在任何实例化中, 例如
tuple_pair<char,short,0,int,long> tp;
seq_pair<0,2,3,void,4,5,6> sp;
编译器也可以区分 ...lhs
参数和 ...rhs
尽我所能。
我不接受任何关于标准为何如此的猜测 - 强调如此 - 但可以 任何人权威地告诉我们为什么 C++ 模板机制不或 这样就不能支持分离多个类模板参数包了吗? 我特别想确认或驳回怀疑 我忽略了一个基本的逻辑障碍。
最佳答案
可变参数模板列表不能作为一流对象进行操作。因此,使用包裹在某些模板对象中的参数包通常更方便。
这就是我将两个类型列表传递给模板类的方式:
// create an empty default implementation
template <typename LeftTuple, typename RightTuple>
class tuplePair {};
// specialise to allow tupled lists of types to be passed in
template <typename ...LHS, typename ...RHS>
class tuplePair<tuple<LHS...>, tuple<RHS...> >
{
// ...
};
//or more catholically:
template <typename ...LHS, typename ...RHS, template<typename...> class tuple_template>
class tuplePair<tuple_template<LHS...>, tuple_template<RHS...>>
{
// ...
};
template<typename... X>
class some_other_tuple {};
int main() {
tuplePair<tuple<char,char,char>, tuple<char,char,char>> tango_tuple;
tuplePair<some_other_tuple<int>, some_other_tuple<char>> other_tuple;
return 0;
}
我在任何情况下都比使用某种分隔符 (void
) 更清晰。作为一般规则语义,支持列表或元组对象而不是简单地使用分隔符更强大(因为它们允许嵌套)并且更容易操作。
附录:
我会冒险给出另一个没有捕获要点的答案,特别是它不权威,希望它可能有所帮助。
我已经通读了可变参数模板提案的草稿,并扫描了 comp.std.C++ 上的所有 196 个线程,其中提到了“可变参数”这个词,似乎这种限制的唯一原因是简单性。特别是起草标准而不是实现的简单性。
我找不到任何关于您提出的泛化的讨论(允许参数包在模板参数列表中的任何位置,其后没有跟一个参数或同类参数包)。然而,讨论了其他概括,例如允许参数包扩展出现在模板特化末尾以外的地方,看起来这些讨论的时间已经用完了。
您有一个有说服力的用例吗?我真的不想成为“给我看一个用例否则我会关闭你”的恶霸,我只是感兴趣。
关于c++ - 为什么可变参数类模板最多只能有一个参数包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24471533/