Skip to content

Instantly share code, notes, and snippets.

@tylov
Last active July 2, 2021 16:46
Show Gist options
  • Save tylov/d7758ed0b5e6e42e47452726b32b6c6b to your computer and use it in GitHub Desktop.
Save tylov/d7758ed0b5e6e42e47452726b32b6c6b to your computer and use it in GitHub Desktop.
Macro overloading support in C.
/* MIT License
*
* Copyright (c) 2021 Tyge Løvset, NORCE, www.norceresearch.no
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef COVERLOAD_INCLUDED
#define COVERLOAD_INCLUDED
/*
Utility for overloading macros by different number of arguments.
Based on https://rextester.com/ONP80107
Example:
#define foo(...) c_OVERLOAD(foo, __VA_ARGS__)
#define foo_0() "Zero"
#define foo_1(x) "One"
#define foo_2(x, y) "Two"
#define foo_3(x, y, z) "Three"
#include <stdio.h>
int main()
{
printf("%s %s %s %s\n", foo(), foo(1), foo(1, 2), foo(1, 2, 3));
}
*/
#define c_OVERLOAD(name, ...) _c_OVERLOAD_SELECT(name, _c_OVERLOAD_NUM_ARGS(__VA_ARGS__))(__VA_ARGS__)
#define _c_OVERLOAD_SELECT(name, num) _c_OVERLOAD_CONCAT(name, num)
#define _c_OVERLOAD_CONCAT(name, num) name ## _ ## num
#define _c_OVERLOAD_NUM_ARGS(...) _c_OVERLOAD_APPLY_ARG_N((_c_OVERLOAD_DETECT_0_ARGS(__VA_ARGS__), _c_OVERLOAD_RSEQ_N))
#define _c_OVERLOAD_APPLY_ARG_N(args) _c_OVERLOAD_ARG_N args
#define _c_OVERLOAD_DETECT_0_ARGS(...) _c_OVERLOAD_PREFIX_ ## __VA_ARGS__ ## SUFFIX
#define _c_OVERLOAD_PREFIX_SUFFIX ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0
#define _c_OVERLOAD_ARG_N(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, \
_12, _13, _14, _15, _16, _17, _18, _19, _20, _21, \
_22, _23, _24, _25, _26, _27, _28, _29, _30, N, ...) N
#define _c_OVERLOAD_RSEQ_N \
31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, \
16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment