Skip to content

Instantly share code, notes, and snippets.

@mtao
Last active July 23, 2024 01:36
Show Gist options
  • Save mtao/58e6859ac4ac2300ddb9e1050b9ed701 to your computer and use it in GitHub Desktop.
Save mtao/58e6859ac4ac2300ddb9e1050b9ed701 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <Eigen/Dense>
#include <concepts>
namespace Eigen {
template <int D, typename Derived>
inline auto& get(Eigen::DenseCoeffsBase<Derived, WriteAccessors>& p) { return p.coeffRef(D); }
template <int D, typename Derived>
inline const auto get(const Eigen::DenseCoeffsBase<Derived,ReadOnlyAccessors>& p) { return p.coeff(D); }
template <typename Derived>
concept StaticSizePlainObjectBase = std::derived_from<Derived,Eigen::PlainObjectBase<Derived>> &&
(Derived::RowsAtCompileTime >0 && Derived::ColsAtCompileTime > 0);
template <typename Derived>
concept StaticSizeEigenBase = std::derived_from<Derived,Eigen::EigenBase<Derived>> &&
(Derived::RowsAtCompileTime >0 && Derived::ColsAtCompileTime > 0);
}
namespace std {
template <typename Derived> requires Eigen::StaticSizeEigenBase<Derived>
struct tuple_size<Derived> {
constexpr static int value = Derived::RowsAtCompileTime * Derived::ColsAtCompileTime;
};
template <size_t D, typename Derived> requires Eigen::StaticSizeEigenBase<Derived> &&
(D < Derived::RowsAtCompileTime * Derived::ColsAtCompileTime)
struct tuple_element<D,Derived> {
using type = typename Derived::Scalar;
};
}
int main(int argc, char * argv[]) {
// We can use a structured binding to populate an eigen vector!
Eigen::Vector3d p;
auto& [x,y,z] = p;
x = 2;
y = 3;
z = 4;
// works for Array, const, int, and size 2!
const Eigen::Array2i q = p.head<2>().cast<int>().array();
auto& [u,v] = q;
// even works on expression templates!
auto [u2,v2] = 2*q;
std::cout << p.transpose() << std::endl;
std::cout << u << "," << v << std::endl;
std::cout << u2 << "," << v2 << std::endl;
// Can use to read blocks, but not write... yet!
Eigen::Matrix3f A;
A.setIdentity();
auto [m,n,o] = A.col(2);
std::cout << m << "," << n << "," << o << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment