如何推导嵌套的容器值类型
How to deduce nested container value type
我有一个存储另一个容器的容器。我需要在嵌套容器的值上为这个容器创建一个迭代器。这个迭代器应该定义一个operator*
,但我不知道要返回的嵌套容器的值类型。我不能保证容器有任何值为的typedef
。唯一给出的是每个容器都有一个合适的operator[]
。如何申报operator*
?
template<typename ContainerType>
struct MyIterator{
MyIterator(ContainerType& container, int32 indexA = 0, int32 indexB = 0)
: Container(container)
, IndexA(indexA)
, IndexB(indexB)
{}
// NestedValueType needs to be replaced or declared somehow
NestedValueType& operator* ()
{
return Container[IndexA][IndexB];
}
private:
ContainerType& Container;
int32 IndexA;
int32 IndexB;
};
附言:我只有C++11功能可用。
您可以使用decltype
:
auto operator*() -> decltype(Container[IndexA][IndexB])
{
return Container[IndexA][IndexB];
}
要做到这一点,您应该将数据成员从类的底部移动到顶部。请参阅此答案以了解原因。
一种替代方案是在每个数据成员访问(decltype(this->Container[this->IndexA][this->IndexB])
)之前放置this->
。
如果您的编译器支持C++14,一个解决方案是以以下方式使用decltype(auto)
:
decltype(auto) operator* () {
return (Container[IndexA][IndexB]);
}
实时演示
相关文章:
- 具有默认模板类型的默认构造函数的类型推导
- 在 lambda 捕获中声明的变量的类型推导
- 推导 std::vector::back() 的返回类型
- 为什么依赖模板类型在部分专用化中不可推导?
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- 参数和参数包的类型推导
- 函数类型参数的模板参数推导
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 递归函数的返回类型推导
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 通过类型别名从构造函数转发模板推导
- 可变参数模板函数参数和引用类型推导
- 是否可以将类型转换推导为C 中的模板类型
- 如何使模板类型的推导与引用一起工作
- 从模板参数类型中推导函数模板参数
- 如何声明一个返回类型是推导出来的函数
- 可调用对象的结果类型的推导
- 在c++中传递函数作为模板类型并推导其类型
- 用asio进行C++11类型的推导
- c++ 03中模板函数返回类型的推导