簡體   English   中英

我需要 std::conditional 但有兩個以上的選擇

[英]I need std::conditional but with more than two choices

事實是,我有堆棧類模板,我想根據從文件中獲取的數字或字符來決定創建哪種類型的對象。 所以代替

if(T=='I')
    {
        myStack<int> teststack;
    }
else if(T=='D')
    {
        myStack<double> teststack;
    }

我想做一些允許我在“if”范圍之外使用堆棧的事情

最接近的是 std::conditional,但在我的情況下,應該是這樣的:

template<int type, class first, class second, class third>

所以我可以像這樣使用它

   int i;
   input>>i;
   myStack<i> teststack;

根據我的數量,它應該是第一種、第二種或第三種類型。 我知道這不是最好的問題,但我只是有點困惑

您獲取i值的方式(從流中)意味着它的值只能在運行時知道。

這意味着std::conditional對您根本不起作用,因為必須在編譯時知道條件表達式。

switch語句可以滿足您的需要,但大多數 C++ 實現本質上都將switch減少到if語句鏈。

您將在您提出的任何解決方案中都有if語句。

有一句老生常談的 C++ 老生常談“首先正確實現,然后開始優化”。 因此,一連串if語句甚至switch語句的幼稚方法是一種完全可以接受的方法,甚至是最好的方法,直到您發現需要更有效的方法。

但是,如果您想消除將i與每個有意義的值進行比較的可能性,您可以使用std::map<char, some-callable-type > 在地圖中查找i的值,並調用相關聯的 callable。

嘗試類似:

#include<iostream>
#include<string>
#include<map>
#include<functional>

template<class T> struct myStack{};

template<class T> int doStuff()
{
    myStack<T> mystack;
    return 0;
}


int main()
{
    char i;
    std::map<char,std::function<int()>> doIt{
        {'i', &doStuff<int>},
        {'d', &doStuff<double>,},
        {'l', []()->int{return 1;}},
        {'s', &doStuff<std::string>}
    };
    std::cin>>i;
    return doIt[i]();
}

( https://godbolt.org/z/fzhJc2 )

如果可能性很小,您甚至可以使用std::array

std::conditional可以組合成一個開關:

using U = std::conditional_t<
    T == 'I',
    First, std::conditional_t<
    T == 'D',
    Second, Third>>;

暫無
暫無

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

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