switch语句的std :: pair? [英] switch statement for an std::pair?
问题描述
我想切换两个整数的可能值,或者在另一个情况下切换两个bool。为了讨论起见,假设我已经做了
I want to switch over possible values of two integers, or in another case two bools. For the sake of discussion, suppose I've done
auto mypair = std::make_pair(foo, bar);
如何实现
switch(mypair) {
case make_pair(true, false): cout << "true and false"; break;
case make_pair(false, true) cout << "false and true"; break;
case default: cout << "something else";
}
(C ++ 14/17也相关,如果这有帮助)?
with C++11? (C++14/17 also relevant if that helps)?
推荐答案
C ++的switch语句没有模式匹配的许多其他语言。
C++'s switch statement doesn't have the pattern matching power of many other languages. You'll need to take a slightly different approach.
这里有一种可能性:
pair_switch(my_pair,
std::make_tuple(true, false, []{ std::cout << "true and false"; }),
std::make_tuple(false, true, []{ std::cout << "false and true"; }));
您提供 std :: pair< bool,bool>
和一组case作为 std :: tuples
,其中前两个元素匹配你传递的对,第三个元素是一个函数调用
You supply a std::pair<bool,bool>
and a set of cases as std::tuples
, where the first two elements match the pair you pass in and the third element is a function to call for that case.
实现有几个模板技巧,但应该非常实用:
The implementation has a few template tricks, but should be pretty usable:
template <typename... Ts>
void pair_switch(std::pair<bool,bool> pair, Ts&&... ts) {
//A table for the cases
std::array<std::function<void()>, 4> table {};
//Fill in the cases
(void)std::initializer_list<int> {
(table[std::get<0>(ts)*2 + std::get<1>(ts)] = std::get<2>(ts), 0)...
};
//Get the function to call out of the table
auto& func = table[pair.first*2 + pair.second];
//If there is a function there, call it
if (func) {
func();
//Otherwise, throw an exception
} else {
throw std::runtime_error("No such case");
}
}
这篇关于switch语句的std :: pair?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!