【问题标题】:Create alias template for any STL container [closed]为任何 STL 容器创建别名模板 [关闭]
【发布时间】:2020-09-15 15:53:03
【问题描述】:

我需要创建一个模板类型来使用任何容器 STL:

例子:

template <typename T>
using STL_container = ...;

并使用:

void PrintVectorOrList(STL_container<int> container) { ... }

void PrintMap(STL_container<std::string, int> container) { ... }

如何制作别名模板?

【问题讨论】:

  • How to do it better? 以何种方式更好?你如何衡量某件事是否更好?为什么简单的using = 不能令人满意? void PrintVectorOrList(STL_container&lt;int&gt; container) 为什么不只是 template &lt;typename T&gt; print_any_container(T container) { .. }? (也许要检查std::enable_if&lt;std::is_same&lt;T::value_type, int&gt; &gt; 或类似的)
  • 在什么方面更好?请解释“更好”的含义
  • 注意vector除了value_type还有分配...
  • 您在寻找 C++20 概念吗?作为ranges' ones
  • 您可以使用模板模板参数,但标准容器有多种不同的模板参数。如果你想写一个通用的Print,你应该尝试使用迭代器。

标签: c++


【解决方案1】:

看来你想要模板函数:

template <typename Container, typename ValueType>
constexpr bool IsContainerOf = std::is_same_v<ValueType, typename Container::value_type>;
// Possibly extra check has begin/end


template <typename Container,
          std::enable_if_t<IsContainerOf<Container, int>, bool> = false>
void PrintVectorOrList(const Container& container)
{
    for (int i : container) {
        std::cout << i << std::endl;
    }
}

template <typename Container,
          std::enable_if_t<IsContainerOf<Container, std::pair<std::string, int>>, bool> = false>
void PrintMap(const Container& container)
{
    for (const auto& [s, i] : container) {
        std::cout << s << ": " << i << std::endl;
    }
}

C++20 将允许概念而不是 SFINAE 具有类似于

的语法
void PrintListOrVector(const Container<int> auto& container) {/*..*/}
void PrintMap(const Container<std::pair<std::string, int>> auto& container) {/*..*/}

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多