簡體   English   中英

如何確定輸入的類型是什么

[英]How to determine, what type do I have on input

我有通過未定義類型的迭代器:

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

知道我的*hayStackIterator是什么類型,能夠根據此信息修改內部邏輯*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>

將內部邏輯放入函數中,並重載該函數:

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);
    }
}

您可以使用STL容器中的typedefs來幫助您使用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
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM