c++ - 为任何 STL 容器创建别名模板
问题描述
我需要创建一个模板类型来使用任何容器 STL,即:
例子:
template <typename T>
using STL_container = ...;
并使用:
void PrintVectorOrList(STL_container<int> container) { ... }
void PrintMap(STL_container<std::string, int> container) { ... }
如何制作别名模板?
解决方案
看来您需要模板功能:
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) {/*..*/}
推荐阅读
- vue.js - 在 NuxtJS 应用程序中覆盖 Tailwind CSS @apply 指令
- css - CSS:传单标记边框保持显示为不良效果
- reactjs - TypeError:react_1.forwardRef 不是函数
- java - 嗨,我如何检查在 java 中接受数字、字符和特殊字符的正则表达式
- sql - sql - 在括号之间获取文本
- javascript - 使用 Tailwind 更改 min-h-full 的值或添加类以设置 min-height
- c++ - 如何将 -std=c++11 配置为默认编译器?
- hyperledger-fabric - 什么情况会导致fabric网络出现状态分叉
- ios - ios上的颤振蓝牙问题
- sql - 尝试在 azure 中创建应用程序,它将基于 SQL 服务器中的 DML 操作将 xml 发布到 URL