簡體   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