[英]I need std::conditional but with more than two choices
Thing is, I have stack class template, and I want to decide which type of object I create based on, say, number, or char I get from file.事实是,我有堆栈类模板,我想根据从文件中获取的数字或字符来决定创建哪种类型的对象。 So instead of
所以代替
if(T=='I')
{
myStack<int> teststack;
}
else if(T=='D')
{
myStack<double> teststack;
}
i wanna do something which allows me to use stack out of "if" scope我想做一些允许我在“if”范围之外使用堆栈的事情
closest thing was std::conditional, but in my case that should work something like that:最接近的是 std::conditional,但在我的情况下,应该是这样的:
template<int type, class first, class second, class third>
so I could use it like所以我可以像这样使用它
int i;
input>>i;
myStack<i> teststack;
And it should be first, second or third type based on number I have.根据我的数量,它应该是第一种、第二种或第三种类型。 I know thats not best question, but I just kinda confused a lot
我知道这不是最好的问题,但我只是有点困惑
The way you are acquiring the value of i
(from a stream) means that its value can only be known at run time.您获取
i
值的方式(从流中)意味着它的值只能在运行时知道。
This means that std::conditional
will not work at all for you, since the conditional expression has to be known at compile time .这意味着
std::conditional
对您根本不起作用,因为必须在编译时知道条件表达式。
A switch
statement will get you what you need, but most implementations C++ essentially reduce a switch
to a chain of if
statements. switch
语句可以满足您的需要,但大多数 C++ 实现本质上都将switch
减少到if
语句链。
You will have if
statements in whatever solution you come up with.您将在您提出的任何解决方案中都有
if
语句。
There is a well-worn C++ truism of "implement correctly first, then start optimizing".有一句老生常谈的 C++ 老生常谈“首先正确实现,然后开始优化”。 So the naïve approach of a chain of
if
statements or even a switch
statement is a perfectly acceptable way of doing this, and even the best way , until you discover you need something more efficient.因此,一连串
if
语句甚至switch
语句的幼稚方法是一种完全可以接受的方法,甚至是最好的方法,直到您发现需要更有效的方法。
However, if you want to eliminate the possibility of comparing i
to every meaningful value, you can use something like a std::map<char,
some-callable-type
>
.但是,如果您想消除将
i
与每个有意义的值进行比较的可能性,您可以使用std::map<char,
some-callable-type
>
。 Look up the value of i
in the map, and call the associated callable.在地图中查找
i
的值,并调用相关联的 callable。
Try something like:尝试类似:
#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 ) ( https://godbolt.org/z/fzhJc2 )
You could even use a std::array
if the number of possibilities is small.如果可能性很小,您甚至可以使用
std::array
。
std::conditional
s can be combined to form a switch: 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.