Is Template Metaprogramming faster than the equivalent C code?

前端 未结 8 2369
旧时难觅i
旧时难觅i 2021-01-02 02:07

Is Template Metaprogramming faster than the equivalent C code ? ( I\'m talking about the runtime performance) :)

8条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 02:20

    If you mean reusable code, then yes without a doubt. Metaprogramming is a superior way to produce libraries, not client code. Client code is not generic, it is written to do specific things.

    For example, look at the qsort from C standard library, and C++ standard sort. This is how qsort works :

    int compare(const void* a, const void* b)
    {
        return (*(int*)a > *(int*)b);
    }
    
    int main()
    {
        int data[5] = {5, 4, 3, 2, 1};
    
        qsort(data, 5, sizeof(int), compare);
    }
    

    Now look at sort :

    struct compare
    {
        bool operator()(int a, int b)
        { return a < b; }
    };
    
    int main()
    {
        int data[5] = {5, 4, 3, 2, 1};
        std::sort(data, data+5, compare());
    }
    

    sort is cleaner, safer and more efficient because the comparison function is inlined inside the sort. That is the benefit of metaprogramming in my opinion, you write generic code, but the compiler produce code like the hand-coded one!


    Another place where I find metaprogramming very beautiful is when you write a library like boost::spirit or boost::xpressive, with spirit you can write EBNF inside C++ and let the compile check the EBNF syntax for you and with xpressive you can write regex and let the compiler check the regex syntax for you also!


    I am not sure if the questioner means by TMP calculating values at compile time. This is an example I wrote using boost :)

    unsigned long greatestCommonDivisor = boost::math::static_gcd<25657, 54887524>::value;
    

    What ever you do with C you can't mimic the above code, basically you have to hand-calculate it then assign the result to greatestCommonDivisor!

提交回复
热议问题