[英]How can I create a container iterator with the container holding a policy type?
[英]How to determine the iterator type for container?
為了將iterator_type
設置為與T
關聯的迭代器類型,我必須為YYY,ZZZ寫什么? 如果可能的話,它應該可以在Visual Studio C ++ 2010中運行(但是一般的標准解決方案也可以)。
template<class T>
struct iterator_for {
typedef YYY<T>::ZZZ type;
}
因此,我想要:
iterator_for<double[3]>::type is double *
iterator_for<std::string>::type is std::string::iterator
iterator_for<char[12]>::type is char *
等等
我有一個模板包裝器類Wrapper<T>
存儲一些可迭代的內容(即容器,字符串或數組),並且我想定義一個函數,該函數返回指向包裝對象的迭代器。 為此,我需要能夠講解與T
對應的迭代器類型。 對於一個數組,相應的迭代器將是一個指針,而對於一個字符串,該字符串是定義為其迭代器類型的任何字符串。
如果您只想將容器與指針分開,則可以嘗試以下操作
template<class T>
struct iterator_for
{
typedef typename T::iterator type;
};
template<class T>
struct iterator_for<T*>
{
typedef T* type;
};
template<class T, std::size_t N>
struct iterator_for<T (&)[N]>
{
typedef T* type;
};
好的,一種可能是(在C ++ 11中,但在VS 2010中不起作用):
typedef typename std::remove_reference<
decltype (
begin ( std::declval<T> () )
)
>::type
type;
我的解決方案是:
typedef decltype(std::begin(std::declval<T&>())) type;
迭代器類型是在T
的實例上調用時std::begin
返回的類型。 std::declval<T&>
返回T&
,我們可以在其上調用std::begin
。
這與JohnB的答案不同,因為我們將對容器類型的引用傳遞給std::begin
。 這是必需的,因為:
std::declval<T>()
返回右值引用( T&&
)。 std::begin
通過非const引用接受其參數。 但是,由於引用崩潰, std::declval<T&>
返回左值引用。
Boost庫已經有了:
#include <boost/range.hpp>
#include <iostream>
#include <string>
#include <vector>
template <typename T> void print_list(const T& container) {
typedef typename boost::range_iterator<const T>::type iter;
for (iter i = boost::begin(container); i != boost::end(container); ++i)
std::cout << *i << ";";
std::cout << "\n";
}
int main() {
double array[] = {1.0,2.0,3.0};
std::string str = "Hello";
std::vector<int> vec(3, 10);
print_list(array); // prints 1;2;3;
print_list(str); // prints H;e;l;l;o;
print_list(vec); // prints 10;10;10;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.