【问题标题】:How to get the type of a container (e.g. int, double,...) from a template? C++如何从模板中获取容器的类型(例如 int、double、...)? C++
【发布时间】:2013-06-07 20:39:30
【问题描述】:

我正在尝试创建一个 C++-Printing-Function,它通过复制算法和之前用户定义的标头打印任何 STL 容器。

我的问题是,我必须通过复制算法打印它,所以我需要 ostream_iterator ("ostream_iterator") 的模板类型?

如何获取模板后面的容器类型

(我用 typeid(cont) 试过了,但没用 - 谢谢!

 template<typename Container>
    void HeaderPrint(Container cont, std::string header = ""  )
    {
        std::cout << header << std::endl;
        copy(cont.begin(),cont.end(), ostream_iterator<typeid(cont)>(cout," "));
        std::cout << std::endl;
    }

【问题讨论】:

  • typeid(cont) 根本不会做你想做的事。看看漂亮的打印机。
  • 你可能不想通过值传递容器。

标签: c++ templates containers behind


【解决方案1】:

标准库容器用容器类型定义value_type

copy(cont.begin(),cont.end(), ostream_iterator<typename Container::value_type>(cout," "));

如果您使用自己的容器类,最好也使用此约定:

template <typename T>
class MyContainer
{
 public:
  typedef T value_type;
 ....
};

【讨论】:

  • 谢谢,对不起,我表达的不清楚。我想知道“ostream_iterator”需要哪种语法我必须如何声明它?
  • 非常感谢 :) - 我的错误是我写了 cont::value_type 而不是 Container::value_type。
【解决方案2】:

juanchopanza answered about container's typedef,但还有另一种方式。

所有标准容器都有begin() 方法。要获取它的类型,请使用decltype。所以,你的方法是:

template<typename Container>
void HeaderPrint(Container cont, std::string header = ""  )
{
    std::cout << header << std::endl;
    copy(cont.begin(),cont.end(), ostream_iterator<decl_type(*cont.begin())>(cout," "));
    std::cout << std::endl;
}

我还是觉得the way juanchopanza said 更好。

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2013-02-05
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多