【问题标题】:Template template variadic parameter specialization模板模板可变参数特化
【发布时间】:2017-10-15 15:50:20
【问题描述】:

我想知道是否可以通过以下方式专门化模板:

template<typename... Ts>
class Typelist { };

template<template<typename> typename... TTs>
class Typelist<TTs<typename>> { };   //I don't know if that is the right syntax, at least the compiler doesn't complain

我希望它作为模板类型列表以及非模板类型列表工作:

template<typename T>
class AT {};

template<typename T>
class BT {};

template<typename T>
class CT {};

int main() {

    using tl1 = Typelist<int, float, double>;   //works fine
    using tl2 = Typelist<AT, BT, CT>;   //gives an error

}

编辑:

如果我将第二个 Typelist 声明为单独的类型,它可以工作...

template<template<typename> typename... TTs>
class Typelist2 { };

//...
using tl2 = Typelist2<AT, BT, CT>;   //compiler doesn't complain and it works fine

我想知道是否可以只对这两种情况使用Typelist,这样Typelist2 就不必是单独的类型。

谁能帮帮我?

【问题讨论】:

  • AT, BT, CT 是类的模板,您没有指定模板类型。如果没有以任何方式说明,编译器应该如何知道这些模板的基础类型?注意:模板是编译时构造。
  • @AlgirdasPreidžius 我相应地编辑了我的问题......
  • 对于同一个参数,您不能让同一个模板有时将一个类型作为参数,而在其他时候将一个模板作为参数。每个模板参数要么是类型参数,要么是非类型参数,要么是模板参数;专业化无法改变这一点。
  • 我认为class Typelist&lt;TTs&lt;typename&gt;&gt; 的语法不正确。

标签: c++ c++11 templates variadic-templates template-specialization


【解决方案1】:

我想知道是否可以在这两种情况下只使用 Typelist,这样 Typelist2 就不必是单独的类型。

我不这么认为。

因为TypeList被定义为template&lt;typename... Ts&gt;template&lt;template&lt;typename&gt; typename... TTs&gt;;两个定义不能一起工作。

我能想到的最好的帮助是为简单类型定义一个 TypeList 基本版本

template <typename ... Ts>
struct TypeList
 {
   // here you can use Ts...
 };

以及容器的特化(其中只有一个类型)如下

template <template <typename> class ... Tts, typename ... Ts>
struct TypeList<Tts<Ts>...>
 {
   // here you can use Ts... and Tts...
 };

您可以在哪里使用TsTts

但这不是一个很好的解决方案,因为您不能将容器 TypeList 简单地定义为

TypeList<AT, BT, CT> tcl;

但您必须添加包含的虚拟 (?) 类型,如下所示

TypeList<AT<int>, BT<float>, CT<double>> tl2;

另一个问题是你不能混合它们,所以

TypeList<AT<int>, BT<float>, double> tl;

调用TypeList 的基本版本(无容器)。

【讨论】:

  • 最后一个问题对我来说没问题,因为我打算使用模板类型或非模板类型,但不能同时使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2015-02-19
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
相关资源
最近更新 更多