Cameron
Cameron

Reputation: 98746

Overloading operators with C++ metaprogramming templates

I'm using some template meta-programming to solve a small problem, but the syntax is a little annoying -- so I was wondering, in the example below, will overloading operators on the meta-class that has an empty constructor cause a (run-time) performance penalty? Will all the temporaries actually be constructed or can it be assumed that they will be optimized out?

template<int value_>
struct Int {
    static const int value = value_;

    template<typename B>
    struct Add : public Int<value + B::value> {  };

    template<typename B>
    Int<value + B::value> operator+(B const&) { return Int<value + B::value>(); }
};

int main()
{
    // Is doing this:
    int sum = Int<1>::Add<Int<2> >().value;

    // any more efficient (at runtime) than this:
    int sum = (Int<1>() + Int<2>()).value;

    return sum;
}

Upvotes: 0

Views: 362

Answers (2)

Cameron
Cameron

Reputation: 98746

Alright, I tried my example under GCC.

For the Add version with no optimization (-O0), the resulting assembly just loads a constant into sum, then returns it.

For the operator+ version with no optimization (-O0), the resulting assembly does a bit more (it appears to be calling operator+).

However, with -O3, both versions generate the same assembly, which simply loads 3 directly into the return register; the temporaries, function calls, and sum had been optimized out entirely in both cases.

So, they're equally fast with a decent compiler (as long as optimizations are turned on).

Upvotes: 2

user2083098
user2083098

Reputation: 36

Compare assembly code generated by g++ -O3 -S for both solutions. It gives same code for both solutions. It actually optimize code to simply return 3.

Upvotes: 0

Related Questions