简体   繁体   English

使用类型特征专门化字符串迭代器的模板功能

[英]Specialize template function for string iterator using type traits

I have a template class which receives two template types T as below: 我有一个模板类,它接收以下两种模板类型T:

Foo( T arg1,T arg2) 
{

}

there is a function in this class which uses T as iterators.this function works just fine for iterators of integral type ,but it should be implemented differently for iterators of std::string type, 此类中有一个函数使用T作为迭代器。此函数对于整数类型的迭代器工作得很好,但对于std :: string类型的迭代器,应以不同的方式实现,

I should : 我应该 :
first enable the first function just for integral types 首先为整数类型启用第一个功能
second specialize the function for iterators of std::string type 第二个专门针对std :: string类型的迭代器的函数

How should I do this?! 我应该怎么做?

Saying 'iteraters of type std::string ' is not very clear. 说“类型为std::string的迭代器”不是很清楚。 You either mean std::string::iterator, or std::iterator< std::string >. 您的意思是std :: string :: iterator或std :: iterator <std :: string>。 I'm assuming the latter since you also mention 'iterator of integral type', in which case the following achieves what you want: 我假设使用后者,因为您还提到了“整数类型的迭代器”,在这种情况下,以下实现了您想要的功能:

#include <iostream>
#include <vector>
#include <string>
#include <type_traits>

template< typename T >
void foo( typename std::enable_if< std::is_integral< typename T::value_type >::value, T >::type a, T b )
{
    std::cout << "integral iterator\n";
}

template< typename T >
void foo( typename std::enable_if< std::is_same< typename T::value_type, std::string >::value, T >::type a, T b )
{
    std::cout << "string iterator\n";
}

int main() 
{
    std::vector< std::string > vecStr;
    std::vector< int > vecInt;

    foo( vecStr.begin(), vecStr.end() );
    foo( vecInt.begin(), vecInt.end() );

    return 0;
}

Note that this only works with iterators ( T needs to have a public typedef value_type , which normal pointers would not have). 请注意,这仅适用于迭代器( T需要具有公共typedef value_type ,而普通指针则没有)。

You're not giving a clear use-case though so I can only assume that this is what you want. 但是,您没有给出明确的用例,因此我只能假设这就是您想要的。

If you need it to work with pointers (since pointers are technically iterators), you can use std::is_pointer, and std::remove_pointer but I'll leave that as an excercise for the reader. 如果您需要它与指针一起使用(因为指针从技术上讲是迭代器),则可以使用std :: is_pointer和std :: remove_pointer,但我将其留给读者练习。

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

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