Implementing a Switch Statement for Non-Integer Constants in C : Unrolling Binary Search with Templates and Macros
The classic switch statement in C is known for its efficiency when selecting actions based on integer values. However, the limitation of using only integers can pose challenges when dealing with non-integer constants.
The Problem: Slow and Complex Alternatives
One approach is to use a series of if statements, but this can be inefficient and hard to maintain. Using data structures like maps to map strings to integers could introduce additional complexity and coding overhead.
Fast and Sorted Binary Search with Macros and Templates
To achieve a fast, clean, and simple implementation, one can utilize macro and template magic. The fastmatch.h library provides a macro-based solution that essentially unrolls a binary search at compile time. The syntax is similar to a switch statement:
NEWMATCH MATCH("asd") some c++ code MATCH("bqr") ... the buffer for the match is in _buf MATCH("zzz") ... user.YOURSTUFF /*ELSE optional */ ENDMATCH(xy_match)
This generates a function xy_match that performs a binary search on the provided cases. The breaks are implicit, and the syntax is sorted.
Update: C 11 Lambdas and Initializer Lists for Enhanced Elegance
With C 11, lambdas and initializer lists provide a more elegant solution:
#include <utility> #include <algorithm> #include <initializer_list> template <typename KeyType, typename FunPtrType, typename Comp> void Switch(const KeyType &value, std::initializer_list<std::pair<const KeyType, FunPtrType>> sws, Comp comp) { // ... implementation omitted for brevity }
This approach uses a lambda function to compare values and a lower_bound algorithm to search for the correct case.
Update 2016: Compile-Time Trie for Unsorted Cases
For unsorted case branches, a more advanced solution utilizes compile-time trie generation in C 11 metaprogramming. The implementation is available in the cttrie library on GitHub.
By harnessing the compiler's advanced code generator, this approach significantly optimizes the search process, offering performance comparable to a switch statement that would require integers as input.
The above is the detailed content of How Can I Efficiently Implement a Switch Statement in C for Non-Integer Constants?. For more information, please follow other related articles on the PHP Chinese website!