首页 > 解决方案 > 如何进入 C++ 容器的 T 如果没有提供 Container::value_type?

问题描述

value_type容器模板包含typedef是很常见的。这使得创建其他模板代码变得容易,最近的概念,它们能够提取Tif only have been givenContainer和 not Container<T>

但是,并非所有容器(或其他模板类)都定义了这样的 a value_type,尤其是较旧的容器。T即使没有它也有可能到达收容物吗?

我知道有一些技巧,比如“如果它是一个迭代器,那么.begin()应​​该返回一个该类型的值”,但这并不能帮助我们编写一个概念要求来检查一个类是否.begin()确实遵循迭代器的要求。

标签: c++templatescontainersc++-conceptstemplate-templates

解决方案


这是一个类似于Quimby 的解决方案但使用部分模板特化的解决方案:

template<typename...>
struct inner_type_impl;

template<template<typename...> typename C, typename T, typename...Args>
struct inner_type_impl<C<T,Args...>>
{
    using type = T;
};

template<typename T>
using inner_type = typename inner_type_impl<T>::type;

这是从 Quimby 的解决方案中借用的演示。


推荐阅读