Created
April 17, 2017 14:21
-
-
Save mtao/d0483e6e001870aa9c82d16129a418f9 to your computer and use it in GitHub Desktop.
an experiment on how to use structured bindings with prvalues (it took me a bit to realize the constness doesn't affect the double& embedded within)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <tuple> | |
//sample vector class | |
struct Vec3 { | |
public: | |
Vec3(const std::initializer_list<double>& a) { std::copy(a.begin(),a.end(),data); } | |
double& operator()(size_t i) { return data[i]; } | |
private: | |
double data[3]; | |
}; | |
//unpacks things into tuples for me as references | |
//Mimics http://stackoverflow.com/a/40958644 | |
template <int... Is> | |
auto unpack_impl(Vec3& a, std::integer_sequence<int,Is...>) { | |
return std::tie( a(Is)... ); | |
} | |
auto unpack(Vec3& a) { | |
return unpack_impl(a,std::make_integer_sequence<int,3>{}); | |
} | |
int main(int argc, char * argv[]) { | |
Vec3 a{{1,2,3}}; | |
//constness is required for the prvalue std::tuple<double&,double&,double&> from unpack to by assignable | |
//however, this just passes references down, which are still mutable | |
const auto& [u,v,w] = unpack(a); | |
//change u,v,w | |
std::tie(u,v,w) = std::make_tuple<double,double,double>(5,12,13); | |
//check that modifying u,v,w affected a | |
auto [x,y,z] = unpack(a); | |
std::cout << x << " " << y << " " << z << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment