Question

I have a template class which receives two template types T as below:

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,

I should :
first enable the first function just for integral types
second specialize the function for iterators of std::string type

How should I do this?!

Was it helpful?

Solution

Saying 'iteraters of type std::string' is not very clear. You either mean std::string::iterator, or 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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top