我正在使用一些模板元编程来解决一个小问题,但是语法有点烦人——所以我想知道,在下面的示例中,在具有空构造函数的元类上重载运算符会导致 (运行时)性能损失?是否会实际构建所有临时对象,或者是否可以假设它们将被优化?
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;
}