Home > Backend Development > C++ > How Can I Efficiently Implement a Switch Statement for Non-Integer Values in C/C ?

How Can I Efficiently Implement a Switch Statement for Non-Integer Values in C/C ?

Linda Hamilton
Release: 2024-12-04 09:08:15
Original
293 people have browsed it

How Can I Efficiently Implement a Switch Statement for Non-Integer Values in C/C  ?

Switch on Non-Integer Values in C/C

Problem:

Determining actions based on non-POD constant elements (e.g., strings) requires workarounds like nested ifs, which can be inefficient and complex. The switch statement, designed for integer values, does not directly support non-integers.

Solution 1: Macro and Template Magic (fastmatch.h)

Using macros and templates, one can create an unrolled binary search at compile time. The syntax is concise, but requires sorted case branches. This approach generates a function with implicit breaks that assigns the relevant match to a buffer.

MATCH("asd")
  some c++ code
MATCH("bqr")
  ... the buffer for the match is in _buf
MATCH("zzz")
  ...  user.YOURSTUFF 
/*ELSE 
  optional
*/
ENDMATCH(xy_match)

xy_match("bqr",youruserdata);
Copy after login

Solution 2: C 11 Lambdas and Initializer Lists

In C 11, lambdas and initializer lists provide a cleaner solution. This approach performs a binary search on a list of key-value pairs, where the key corresponds to the non-integer value and the value is a function pointer. The found function is then invoked.

#include <utility>
#include <algorithm>
#include <initializer_list>

template <typename KeyType, typename FunPtrType, typename Comp>
void Switch(const KeyType &amp;value, std::initializer_list<std::pair<const KeyType, FunPtrType>> sws, Comp comp) {
  // ... search and invoke code
}

Switch("ger",{ 
    {"asdf",[]{ printf("0\n"); }},
    {"bde",[]{ printf("1\n"); }},
    {"ger",[]{ printf("2\n"); }}
  },[](const char *a,const char *b){ return strcmp(a,b)<0;});
Copy after login

Solution 3: Compile Time Trie (cttrie)

In C 11, a compile-time trie approach can handle unsorted case branches effortlessly. Advanced metaprogramming techniques generate a search-trie at compile time, utilizing switch statements in each trie node to efficiently redirect execution flow.

The full implementation is available at github: smilingthax/cttrie.

The above is the detailed content of How Can I Efficiently Implement a Switch Statement for Non-Integer Values in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template