首页 > 解决方案 > 为任何 STL 容器创建别名模板

问题描述

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

例子:

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

并使用:

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

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

如何制作别名模板?

标签: c++

解决方案


看来您需要模板功能:

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) {/*..*/}

推荐阅读