【问题标题】:typedef'd STL container type as template parametertypedef'd STL 容器类型作为模板参数
【发布时间】:2014-06-17 22:05:18
【问题描述】:

我想知道是否可以使用 typedef'd 容器作为模板参数。我正在尝试以下方法:

template<typename T>
using containerT = std::vector<T>;

template <template<class T, class = std::allocator<T> > class container_type = containerT >
struct nodeData {
    container_type<int> param;
};

int main()
{    
    nodeData<> nd;
}

这会导致 GCC 4.8 出现编译错误:

需要一个类型为“模板类”的模板 container_type', 得到'模板使用 containerT = std::vector'

有人知道怎么做吗?

谢谢

【问题讨论】:

    标签: c++ templates stl


    【解决方案1】:

    containerT只有一个模板参数,所以模板模板参数必须匹配:

    template <template<class> class container_type = containerT >
    

    但是,我怀疑您希望能够将标准容器作为模板参数,因此您希望这样做:

    template<class T, class Allocator = std::allocator<T>>
    using containerT = std::vector<T, Allocator>;
    

    现在您可以使用containerT 作为您在问题中提供的函数模板的模板参数。

    【讨论】:

      【解决方案2】:

      您可以将模板包装在一个类型中,从而延迟其实例化。这使得模板成为元编程世界的一等公民:

      template<template<typename...> class T>
      struct wrapper
      {
          template<typename... ARGS>
          using instance = T<ARGS...>;
      };
      
      template<typename WRAPPER , typename... ARGS>
      using instance = typename WRAPPER::template instance<ARGS...>;
      

      现在您可以使用包装器作为类型可选模板参数:

      using container_type = wrapper<std::vector>;
      
      template <typename CONTAINER = container_type>
      struct nodeData {
          instance<CONTAINER,int> param;
      };
      

      现在您的用例完美运行:

      int main()
      {
          nodeData<> node;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        • 2021-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        相关资源
        最近更新 更多