خرید بک لینک

When working with keyboard input in a situation like the one shown in the next simplified example:

// abc.hpp

#pragma once
#include <array>

// ranges of integer values in the enum could be contiguous or
// not, so question is for a general scenario. However if being
// a contiguous range of integer values makes things notably
// simpler, then certainly it'd be interesting to know about it.
enum FileType : int {
  JSON = 1,
  YAML = 2,
  XML = 3
};

constexpr std::array<FileType, 3> file_types {
  FileType::JSON,
  FileType::YAML,
  FileType::XML
};

/*
constexpr std::array<FileType, 3> file_types {
  JSON,
  YAML,
  XML
};
*/
// main.cpp

#include <algorithm>
#include <iostream>
#include "abc.hpp"

int main()
{
  std::cout << "Enter the file type:n";
  int ft{0};
  std::cin >> ft;
  
  if (std::ranges::contains(file_types, ft))  // if (std::ranges::contains(FileType, ft)): error "type name is not allowed"
  {
    std::cout << "valid inputn";
  }
  else // if (!std::ranges::contains(file_types, ft))
  {
    std::cout << "invalid inputn";
    
    return 1;
  }
   
  return 0;

Is there a more direct way to check if the input value is present among the enum defined range of values?

In this example that process is being done by manually adding the enum values into a std::array and then with std::ranges::contains() checking if the input value is present in the array, but this presents a scalability problem in case the enum could have tens of possible options.


Preferences:

  • A solution based on what comes with C++ and with the STL, without external libraries.
  • A solution without the need of extra custom functions (helpers, wrappers, etc.).
  • C++23 or newer versions are welcome.

برچسب: نویسنده: استخدام کار تاريخ: شنبه 7 شهريور 1405 ساعت: 2:40

صفحه بندی