如何将常量限定符添加到 vector<>::p ointer?

How to add const qualifier to vector<>::pointer?

本文关键字:lt ointer gt vector 常量 添加      更新时间:2023-10-16

我正在尝试将const指针传递给 std::vector的元素到一个函数,但我似乎无法正确地获得该函数的签名。我一定在这里缺少一些微不足道的东西,但是我很困惑。

这是重现问题的最小示例:

#include <vector>
#include <functional>
class Image { void* ptr; };
using ImageConstRefArray = std::vector< std::reference_wrapper< Image const >>;
template< typename T = void, typename... OtherTs >
void TestDataType( const ImageConstRefArray::pointer images ) {
   // stuff.
   TestDataType< OtherTs... >( images + 1 );
}
template<>
inline void TestDataType<>( const ImageConstRefArray::pointer /*images*/ ) {} // End of iteration
template< typename... Types >
void Function( ImageConstRefArray const& images ) {
   TestDataType< Types... >( images.data() );
}
int main() {
   Image img1, img2;
   ImageConstRefArray array{ img1, img2 };
   Function( array );
}

这是GCC(5.4)错误消息:

test.cpp: In instantiation of ‘void Function(const ImageConstRefArray&) [with Types = {}; ImageConstRefArray = std::vector<std::reference_wrapper<const Image> >]’:
test.cpp:24:20:   required from here
test.cpp:18:28: error: no matching function for call to ‘TestDataType(const std::reference_wrapper<const Image>*)’
    TestDataType< Types... >( images.data() );
                            ^
test.cpp:9:6: note: candidate: template<class T, class ... OtherTs> void TestDataType(std::vector<std::reference_wrapper<const Image> >::pointer)
 void TestDataType( const ImageConstRefArray::pointer images ) {
      ^
test.cpp:9:6: note:   template argument deduction/substitution failed:
test.cpp:18:41: note:   cannot convert ‘(& images)->std::vector<_Tp, _Alloc>::data<std::reference_wrapper<const Image>, std::allocator<std::reference_wrapper<const Image> > >()’ (type ‘const std::reference_wrapper<const Image>*’) to type ‘std::vector<std::reference_wrapper<const Image> >::pointer {aka std::reference_wrapper<const Image>*}’
    TestDataType< Types... >( images.data() );

基本上,它试图将const std::reference_wrapper<const Image>*放入std::reference_wrapper<const Image>*中。该函数的签名为const ImageConstRefArray::pointer作为参数。如果该const不能使指针成为const指针,那么我该如何编写函数签名?是写出const std::reference_wrapper<const Image>*的唯一解决方案吗?这解决了问题,但我宁愿用ImageConstRefArray来写它。

对于const ImageConstRefArray::pointerconst在指针本身上有资格,因此它将是std::reference_wrapper<const Image>* constconst指针指向非CONST),而不是std::reference_wrapper<const Image> const *(非CONST Pointer to const)。(请注意const的不同位置。)

您应该改用std::vector::const_pointer,这将为您提供const T的指针类型。例如

template< typename T = void, typename... OtherTs >
void TestDataType( ImageConstRefArray::const_pointer images ) {
   // stuff.
   TestDataType< OtherTs... >( images + 1 );
}
template<>
inline void TestDataType<>( ImageConstRefArray::const_pointer /*images*/ ) {} // End of iteration