繁体   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