我有一个问题,我需要检测给定类型是否是已知嵌套类型的实例,例如std::vector::iterator
在编译时。我想创建类型特征is_std_vector_iterator
:
#include <type_traits>
#include <vector>
template<typename T> struct is_std_vector_iterator : std::false_type {};
template<typename T, typename Allocator>
struct is_std_vector_iterator<typename std::vector<T,Allocator>::iterator>
: std::true_type
{};
int main()
{
return 0;
}
但我收到编译器错误:
$ g++ -std=c++0x test.cpp
test.cpp:7: error: template parameters not used in partial specialization:
test.cpp:7: error: ‘T’
test.cpp:7: error: ‘Allocator’
是否可以检查依赖类型,例如std::vector<T,Allocator>::iterator
?
这是这种特征的一个激励用例:
template<typename Iterator>
Iterator my_copy(Iterator first, Iterator last, Iterator result, std::true_type)
{
// iterators are just pointer wrappers; call memcpy
memcpy(&*result, &*first, sizeof(typename Iterator::value_type) * last - first);
return result + last - first;
}
template<typename Iterator>
Iterator my_copy(Iterator first, Iterator last, Iterator result, std::false_type)
{
// use a general copy
return std::copy(first, last, result);
}
template<typename Iterator>
Iterator my_copy(Iterator first, Iterator last, Iterator result)
{
// dispatch based on the type of Iterator
return my_copy(first, last, result, typename is_std_vector_iterator<Iterator1>::type())
}