繁体   English   中英

如何将const限定符添加到vector <> :: pointer?

[英]How to add const qualifier to vector<>::pointer?

我试图将指向std::vector元素的const指针传递给函数,但似乎无法正确获得函数的签名。 我一定在这里缺少一些琐碎的东西,但是我很困惑。

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

#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>* const (指向非const的const指针),而不是std::reference_wrapper<const Image> const * (指向const非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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM