0

我有未定义类型的迭代器:

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

并且很高兴知道我*hayStackIterator能够根据这些信息修改内部逻辑的类型是什么......是否有一些简单的功能可以制作这样的东西?

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

我可以使用这些includes

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

2 回答 2

3

将内部逻辑放入函数中,并重载该函数:

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);
    }
}
于 2013-04-20T03:46:51.523 回答
1

您可以使用typedefs来自 STL 的容器来帮助您使用 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
    }

}
于 2013-04-20T03:57:14.037 回答