容器模板包含 value_type
是很常见的类型定义。这使得创建其他模板代码、最新概念变得容易,这些代码能够提取 T
如果只给了 Container
而不是 Container<T>
.
然而,并非所有容器(或其他模板类)都定义了这样一个 value_type
,尤其是年纪大的。
是否有可能到达包含的T
即使没有它?
我知道有一些技巧,比如“如果它是一个迭代器,那么 .begin()
应该返回那个类型的值”,但这对我们没有帮助,例如编写一个概念需求来检查类的 .begin()
确实遵循迭代器的要求。
最佳答案
这是一个类似于 Quimby's solution 的解决方案但改用部分模板特化:
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;
这是一个 demo这是从 Quimby 的解决方案中借用的。
关于c++ - 如果没有提供 Container::value_type,如何获取 C++ Container<T> 的 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66538400/