Martin Dvoracek
Martin Dvoracek

Reputation: 1738

How to determine, what type do I have on input

I've got iterator through undefined type:

 for (typename Type::const_iterator hayStackIterator = hayHeap.begin(); hayStackIterator != hayHeap.end(); ++hayStackIterator) {
           //some inner logic
}

and it would be nice, to know what type is my *hayStackIterator to be able to modify the inner logic pursuant this information... Is there some simple function to make something like this?

if (*hayStackIterator.isInstanceOf(vector<string>){
//do something
} else if (*hayStackIterator.isInstanceOf(string){
//do something else
}

I can use these includes:

#include <cctype>
#include <iostream>
#include <iomanip>
#include <set>
#include <list>
#include <map>
#include <vector>
#include <queue>
#include <string>

Upvotes: 0

Views: 73

Answers (2)

stardust
stardust

Reputation: 5998

You can use the typedefs from the STL containers to help you with SFINAE.

template<typename Type> 
function flunk(const Type& hayHeap) {

    typedef typename Type::value_type inner_type;   // STL container typedef
                     ^^^^^^^^^^^^^^^^
    // if Type = vector<string> -> inner_type = string
    // if Type = string         -> inner_type = char

    inner_type start = inner_type();  // initialize start to default.

    for (typename Type::const_iterator hayStackIterator = hayHeap.begin(); hayStackIterator != hayHeap.end(); ++hayStackIterator) {
               //some inner logic
    }

}

Upvotes: 1

Mankarse
Mankarse

Reputation: 40633

Put the inner logic in a function, and overload that function:

void innerLogic(vector<string> const& vec) {
    //do something
}

void innerLogic(string const& str) {
    //do something else
}

void loop() {
    for (typename Type::const_iterator hayStackIterator = hayHeap.begin();
         hayStackIterator != hayHeap.end();
         ++hayStackIterator)
    {
        innerLogic(*hayStackIterator);
    }
}

Upvotes: 3

Related Questions