一、引言
以下是几行浅薄而简洁的代码,聊聊add函数有哪几种写法。抛砖引玉,也许在你实际的项目中会带来些许的收益。
二、知识点
知识点比较简单: 左值和右值引用,std::move
的移动语义,模版等
三、代码(* 自己看自己品,注意有雷)
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include <QDebug>#include <iostream>
#define MYTRACE() do{ qDebug() << __FUNCTION__ << __LINE__;}while(0);class Example {
public:template<typename T>static bool willOverflow(T a, T b) {qDebug() << "T number :" << std::numeric_limits<T>::max();bool ok = (a > 0 && b > std::numeric_limits<T>::max() - a)|| (a < 0 && b < std::numeric_limits<T>::min() - a);if(ok) throw std::overflow_error("Overflow detected");return ok;}auto add(int x,int y) &{MYTRACE();try {willOverflow(x, y);} catch (const std::exception& e) {qDebug() << e.what();}return x+y;}auto add(int x, int y) && -> int{MYTRACE();try {willOverflow(x, y);} catch (const std::exception& e) {qDebug() << e.what();}return x + y;}template<typename T>T add(T val){return val;}template<typename T,typename... Args>auto add(T first,Args... args){return first + add(args...);}template<typename T>auto add(std::initializer_list<T> l) {MYTRACE();static_assert(std::is_same<T,double>::value || std::is_integral<T>::value,"must be double or int.");return std::accumulate(l.begin(),l.end(),0);}
};int main() {Example example;std::cout << example.add(10,10) << std::endl;std::cout << example.add<int>({5,10,15}) << std::endl;int sum1 = example.add<int>(1, 2, 3, 4, 5);double sum2 = example.add<double>(1.1, 2.2, 3.3, 4.4, 5.5);std::cout << "Sum of integers: " << sum1 << std::endl;std::cout << "Sum of doubles: " << sum2 << std::endl;// Call add() on an rvalue objectint result = Example().add(5, 10);std::cout << "Result: " << result << std::endl;std::cout << std::move(example).add(5,10) << std::endl;return 0;
}