简体   繁体   中英

Is it possible to pass parameters into a function using a switch statement in c++?

Is there any way to pass parameters into functions using switch statements in c++? What I am trying to achieve is turning a series of if statements into one switch statement.

As an example, I'd like to turn this:

if (function(a)) {
  //code
}

if (function(b)) {
  //code
}

if (function(c)) {
  //code
}

into this:

switch (function(a/b/c)) {
case a:
  //code
case b:
  //code
case c:
  //code
}

The function returns true or false depending on whether or not a, b, or c is active. It is important to note that a, b, and c would indeed be constants, but the function itself would determine whether or not they're currently active. The problem I am working on is whether or not a key is currently pressed when the function is given the key code to check. It looks something like this:

if (isKeyPressed(Key::A)) {
  //code
}

Is this possible or does it break what a switch statement fundamentally is?

That is not how a switch is used. It would need to look more like this instead:

switch (someValue)
{
case value1:
  function(a);
  break;
case value2:
  function(b);
  break;
case value3:
  function(c);
  break;
}

If that is not what you are looking for, then the ?: operator may work for you, depending on what your inputs actually are, eg:

function( condition1 ? a : (condition2 ? b : c) );

Or, maybe you are trying to calling the function 1 time and get different kinds of output depending on the input, that you can then test for? If so, then std::variant may be what you are looking for, eg:

std::variant<a,b,c> function()
{
  return ...;
}

auto v = function(input);
if (std::holds_alternative<a>(v)) {
  //code
}

else if (std::holds_alternative<b>(v)) {
  //code
}

else if (std::holds_alternative<c>(v)) {
  //code
}

Or:

auto v = function(input);
switch (v.index()) {
  case 0: // a
    //code
    break;
  case 1: // b
    //code
    break;
  case 2: // c
    //code
    break;
}

Or:

auto v = function(input);
std::visit([](auto&& arg) {
  using T = std::decay_t<decltype(arg)>;
  if constexpr (std::is_same_v<T, a>) {
    // code
  }
  else if constexpr (std::is_same_v<T, b>) {
    // code
  }
  else if constexpr (std::is_same_v<T, c>) {
    // code
  }
}, v);

Or:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

auto v = function(input);
std::visit(overloaded {
  [](a arg) { /* code */ },
  [](b arg) { /* code */ },
  [](c arg) { /* code */ },
}, v);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM