#include <iostream>
#include "common/log.h"
#include <limits>
#include <vector>
#include <span>
#include <array>
#include <type_traits>
#include <cmath>
#include <memory>
#include <variant>
#include <cassert>
using namespace AdsonLib;
//Eigen实现原理,表达式模板与延时计算
template<typename T, typename U, typename OP>
struct BE{
BE(const T &l, const U &r, const OP &o):L(l),R(r), op(o){}
auto operator()()const {
return op(L, R);
}
protected:
T L;
U R;
OP op;
};
template<typename T, typename U = void>
constexpr bool is_conainter_v = false;
template<typename T, typename U, typename OP>
struct BCE : private BE<T, U, OP>{
using Base = BE<T, U, OP>;
using Base::Base;
auto operator[](size_t i) {
assert(i < size());
return Base::op(Base::L[i], Base::R[i]);
}
size_t size() const {
assert(Base::L.size() == Base::R.size());
return Base::L.size();
}
};
//添加推导规则
template<typename T, typename U, typename OP>
BCE(T, U, OP) -> BCE<T, U, OP>;
//限制容器,并重载operator+
template<typename T>
constexpr bool is_conainter_v<T, std::void_t<typename T::value_type, typename T::iterator>> = true;
template<typename T, typename U, typename OP>
constexpr bool is_conainter_v<BCE<T,U,OP>> = true;
template<typename T, typename U, typename = std::enable_if_t<is_conainter_v<T> && is_conainter_v<U>>>
auto operator+(const T &a, const U &b) {
return BCE(a, b, [](auto x, auto y){
return x + y;
});
}
int main(int argc, char *argv[]) {
auto plus = [](auto && x, auto && y) ->int { return x + y; };
BE be(2, 3, plus);
LOG(INFO) << "add value: " << be() * 3.0;
std::vector<int> a{1,2,3}, b{3,4,5};
LOG(INFO) << "add vec: " << BCE(a, b, plus)[0];
//重载operator+就能这样
auto y = a + b + a + b;
LOG(INFO) << "add vec: " << y[1];
}
C++20 expression template and delay calculation, Eigen implementation principle
Guess you like
Origin blog.csdn.net/wyg_031113/article/details/128301533
Ranking