How to elegantly implement a series of functions in different type versions using pure C?

后端 未结 5 685
北恋
北恋 2020-12-30 09:53

I want to write several functions that are only different in the types of arguments. I know C++ has template to handle this problem well (not very well yet thou

5条回答
  •  梦毁少年i
    2020-12-30 10:17

    If you think using the C preprocessor is awkward and hard to debug, how about writing a script in some more convenient language to generate a .c file you can #include? Most modern scripting languages come with some sort of template engine, but since your requirements are simple enough, it doesn't have to be any more complex than this;

    #/bin/sh
    for t in int double char mytype; do
        cat <<____HERE
        $t add_$t ($t a, $t b) {
            return (a + b);
        }
    ____HERE
    done >generated.c
    

    The resulting file will be plain-jane straightforward C which should be reasonably simple to debug and change.

提交回复
热议问题