I have been writing a set of classes to allow for a simple python-like zip-function. The following snippet works (almost) just as expected. However, the two variables a and b are not const.
std::vector<double> v1{0.0, 1.1, 2.2, 3.3};
std::vector<int> v2{0, 1, 2};
for (auto const& [a, b] : zip(v1, v2))
{
std::cout << a << '\t' << b << std::endl;
a = 3; // I expected this to give a compiler error, but it does not
std::cout << a << '\t' << b << std::endl;
}
I have been using gcc 7.3.0.
Here is the MCVE:
#include <iostream>
#include <tuple>
#include <vector>
template <class ... Ts>
class zip_iterator
{
using value_iterator_type = std::tuple<decltype( std::begin(std::declval<Ts>()))...>;
using value_type = std::tuple<decltype(*std::begin(std::declval<Ts>()))...>;
using Indices = std::make_index_sequence<sizeof...(Ts)>;
value_iterator_type i;
template <std::size_t ... I>
value_type dereference(std::index_sequence<I...>)
{
return value_type{*std::get<I>(i) ...};
}
public:
zip_iterator(value_iterator_type it) : i(it) {}
value_type operator*()
{
return dereference(Indices{});
}
};
template <class ... Ts>
class zipper
{
using Indices = std::make_index_sequence<sizeof...(Ts)>;
std::tuple<Ts& ...> values;
template <std::size_t ... I>
zip_iterator<Ts& ...> beginner(std::index_sequence<I...>)
{
return std::make_tuple(std::begin(std::get<I>(values)) ...);
}
public:
zipper(Ts& ... args) : values{args...} {}
zip_iterator<Ts& ...> begin()
{
return beginner(Indices{});
}
};
template <class ... Ts>
zipper<Ts& ...> zip(Ts& ... args)
{
return {args...};
}
int main()
{
std::vector<double> v{1};
auto const& [a] = *zip(v).begin();
std::cout << a << std::endl;
a = 2; // I expected this to give a compiler error, but it does not
std::cout << a << std::endl;
}
You have a tuple of a reference, which means that the reference itself will be const qualified (which is ill-formed but in this context ignored), not the value referenced by it.
int a = 7;
std::tuple<int&> tuple = a;
const auto&[aa] = tuple;
aa = 9; // ok
If you look how std::get is defined, you'll see that it returns const std::tuple_element<0, std::tuple<int&>>& for the structured binding above. As the first tuple element is a reference, the const& has no effect, and thus you can modify the return value.
Really, it's same thing if you have a class pointer/reference member that you can modify in a const qualified member function (the value pointed/referenced that is).
Related
I need to define the return types (???? in code) after a sum with 2 parameters pack! My objective is to define a Tuple class (like std::tuple) and to implement for example here, the addition between two tuples of the same length and compatible type), here is a code snippet to understand :
template<class FirstType, class ... Types>
class Tuple{
....
template <typename ... OtherTypes>
const Tuple<????> operator+(Tuple<OtherTypes...>& other) const{...}
...
}
The problem is that "int + double" should return me a double for example! I looked on the std::common_type side, but I don't see either.
A tuple is constructed as follows:
private:
FirstType m_first ;
Tuple<Types...> m_next ;
m_first contains the value, and,
m_next contains the next tuple by removing a value.
This is my way of storing the different types although there is another way with a hereditary approach.
I have another class with a template for the recursive case.
So I don't see how to get the final return type, I have a get function where I used a getHelper<...> structure to return the correct type but here it's different again. I don't want to use AUTO which can cause me problems and which is not magic.
Thank you in advance for your answers.
Example : Tuple<int,double>(3,4.4) + Tuple<double,double>(3.1,3.1) = Tuple<DOUBLE,DOUBLE>(6.5,7.5)
See here for how to elementwise add two tuples https://stackoverflow.com/a/50815600/4117728. The following build on this answer. What is left to add is just to get the common type tuple:
template <typename T1,typename T2>
struct common_tuple;
template <typename...T1,typename...T2>
struct common_tuple< std::tuple<T1...>,std::tuple<T2...>> {
using type = std::tuple<std::common_type_t<T1,T2>...>;
};
Then the answer linked above can be adjusted to:
namespace internal
{
template<typename T,typename S, size_t... Is>
common_tuple<T,S>::type add_rhs_to_lhs(T& t1, const S& t2, std::integer_sequence<size_t, Is...>)
{
return std::make_tuple( (std::get<Is>(t1) + std::get<Is>(t2))... );
}
}
template <typename...T,typename...S>
std::tuple<std::common_type_t<T,S>...> operator + (std::tuple<T...> lhs, const std::tuple<S...>& rhs)
{
return internal::add_rhs_to_lhs(lhs, rhs, std::index_sequence_for<T...>{});
}
int main(int argc, char *argv[])
{
auto a = std::make_tuple(1,2,4);
auto b = std::make_tuple(1.0,2.0,4.0);
auto c = a + b;
std::cout << std::get<0>(c) << "\n";
std::cout << std::get<1>(c) << "\n";
std::cout << std::get<2>(c) << "\n";
}
However, a + b already yields the common type, hence you can simply use auto:
#include <tuple>
#include <iostream>
namespace internal
{
template<typename T,typename S, size_t... Is>
auto add_rhs_to_lhs(T& t1, const S& t2, std::integer_sequence<size_t, Is...>)
{
return std::make_tuple( (std::get<Is>(t1) + std::get<Is>(t2))... );
}
}
template <typename...T,typename...S>
auto operator + (std::tuple<T...> lhs, const std::tuple<S...>& rhs)
{
return internal::add_rhs_to_lhs(lhs, rhs, std::index_sequence_for<T...>{});
}
int main(int argc, char *argv[])
{
auto a = std::make_tuple(1,2,4);
auto b = std::make_tuple(1.0,2.0,4.0);
auto c = a + b;
std::cout << std::get<0>(c) << "\n";
std::cout << std::get<1>(c) << "\n";
std::cout << std::get<2>(c) << "\n";
}
I've encountered strange behavior when trying to construct a tuple of references from a mix of tuples and integral values.
Given the following:
struct A { int v = 1; };
struct B { int v = 2; };
struct C { int v = 3; };
A a;
std::tuple<B,C> tpl;
I'm trying to create a third tuple which holds references to all instances, so that each instance's v will be assignable and readable through it.
Seems simple enough using templates
template <class Tuple, size_t... Is>
constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) {
return std::tuple_cat(std::tie(std::get<Is>(t))...);
// or
// return std::make_tuple(std::ref(std::get<Is>(t))...);
}
template <class...Args>
constexpr auto as_ref(std::tuple<Args...>& t) {
return as_ref_impl(t, std::index_sequence_for<Args...>{});
}
and then
auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl));
which builds fine (in both versions).
Unfortunately only the parts of the reference tuple (ref_tpl), which originate from integral values, can be assigned or read from successfully.
I'm using C++14 and gcc 9.3.0.
Any ideas, or insight why this does not work, are very welcome!
Minimal working example:
#include <iostream>
#include <tuple>
#include <type_traits>
#include <utility>
#include <functional>
struct A { int v = 1; };
struct B { int v = 2; };
struct C { int v = 3; };
A a;
std::tuple<B,C> tpl;
template <class Tuple, size_t... Is>
constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) {
//return std::tuple_cat(std::tie(std::get<Is>(t))...);
return std::make_tuple(std::ref(std::get<Is>(t))...);
}
template <class...Args>
constexpr auto as_ref(std::tuple<Args...>& t) {
return as_ref_impl(t, std::index_sequence_for<Args...>{});
}
int main() {
using std::cout;
auto ref_tpl = std::tuple_cat(std::tie(a), as_ref(tpl));
// prints 1 2 3, as expected.
cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl;
std::get<0>(ref_tpl).v = 8; // works
std::get<1>(ref_tpl).v = 9; // does not work
std::get<2>(ref_tpl).v = 10; // does not work
// should output 8 9 10 instead outputs 8 2 3
cout << a.v << std::get<0>(tpl).v << std::get<1>(tpl).v << std::endl;
// should output 8 9 10, instead outputs garbage.
cout << std::get<0>(ref_tpl).v << std::get<1>(ref_tpl).v << std::get<2>(ref_tpl).v << std::endl;
return 0;
}
This is a simple typo:
constexpr auto as_ref_impl(Tuple t, std::index_sequence<Is...>) {
Tuple is taken by value, so a local copy is made, and the reference is made relative to it.
You should take Tuple by reference instead,
constexpr auto as_ref_impl(Tuple& t, std::index_sequence<Is...>) {
Your as_ref_impl needs to take the Tuple parameter by reference, otherwise you are taking a std::ref to a function local. This explains the unmodified values of tpl, and the garbage values in ref_tpl.
Do this instead:
template <class Tuple, size_t... Is>
// note the reference parameter
constexpr auto as_ref_impl(Tuple &t, std::index_sequence<Is...>) {
return std::make_tuple(std::ref(std::get<Is>(t))...);
}
Here's a demo.
I'm using C++17. I'd like to get an element of a tuple that satisfies some type trait. It would be amazing if the trait could be supplied generically, but I'd be satisfied with a specific function for a certain trait. Usage might look something like this:
auto my_tuple = std::make_tuple { 0.f, 1 };
auto basic = get_if_integral (my_tuple);
auto fancy = get_if<std::is_floating_point> (my_tuple);
std::cout << basic; // '1'
std::cout << fancy; // '0.f'
Ideally this would fail to compile if more than one element satisfies the trait, like std::get (std::tuple).
Here's a surprisingly simple way without using recursion:
template <template <typename...> typename T, typename... Ts>
constexpr int index_of_integral(const T<Ts...>&)
{
const bool a[] = { std::is_integral_v<Ts>... };
for (int i = 0; i < sizeof...(Ts); ++i) if (a[i]) return i;
return -1;
}
template <typename T>
constexpr decltype(auto) get_if_integral(T&& t)
{
return std::get<index_of_integral(t)>(std::forward<T>(t));
}
int main()
{
constexpr auto t = std::make_tuple(3.14, 42, "xyzzy");
static_assert(get_if_integral(t) == 42);
}
It could easily be extended to be parametrized on the trait.
The only things that make it C++17 are the is_integral_v variable template and the single-argument static_assert. Everything else is C++14.
Note that in C++20 the for loop could be replaced with std::find and std::distance.
Ideally it should throw an exception instead of returning -1, but compilers don't seem to like that.
Inspired by this answer.
If I understand correctly what you want... I propose an helper struct gf_h ("get first helper") as follows
template <std::size_t, bool ...>
struct gf_h
{ };
template <std::size_t I, bool ... Bs>
struct gf_h<I, false, Bs...> : public gf_h<I+1u, Bs...>
{ };
template <std::size_t I, bool ... Bs>
struct gf_h<I, true, Bs...> : public std::integral_constant<std::size_t, I>
{ };
and a couple of functions that use it:
template <typename ... Us,
std::size_t I = gf_h<0, std::is_integral<Us>::value...>::value>
auto get_first_integral (std::tuple<Us...> const & t)
{ return std::get<I>(t); }
template <typename ... Us,
std::size_t I = gf_h<0, std::is_floating_point<Us>::value...>::value>
auto get_first_floating (std::tuple<Us...> const & t)
{ return std::get<I>(t); }
Observe that are SFINAE enabled/disabled functions, so are enabled only if there is an integral (or float) value in the tuple
The following is a full compiling example
#include <tuple>
#include <iostream>
template <std::size_t, bool ...>
struct gf_h
{ };
template <std::size_t I, bool ... Bs>
struct gf_h<I, false, Bs...> : public gf_h<I+1u, Bs...>
{ };
template <std::size_t I, bool ... Bs>
struct gf_h<I, true, Bs...> : public std::integral_constant<std::size_t, I>
{ };
template <typename ... Us,
std::size_t I = gf_h<0, std::is_integral<Us>::value...>::value>
auto get_first_integral (std::tuple<Us...> const & t)
{ return std::get<I>(t); }
template <typename ... Us,
std::size_t I = gf_h<0, std::is_floating_point<Us>::value...>::value>
auto get_first_floating (std::tuple<Us...> const & t)
{ return std::get<I>(t); }
int main()
{
auto tup1 = std::make_tuple(3.f, 2., 1, 0);
std::cout << get_first_integral(tup1) << std::endl; // 1
std::cout << get_first_floating(tup1) << std::endl; // 3
auto tup2 = std::make_tuple("abc", 4, 5);
std::cout << get_first_integral(tup2) << std::endl; // 4
// std::cout << get_first_floating(tup2) << std::endl; // error
auto tup3 = std::make_tuple("xyz", 6., 7.f);
// std::cout << get_first_integral(tup3) << std::endl; // error
std::cout << get_first_floating(tup3) << std::endl; // 6
}
Ok, I figured out a way to accomplish this in a way that is not generic over the trait, but that's good enough for my current purpose. Using if constexpr this really doesn't look too bad. I'm sure this isn't hugely idiomatic, but it works for me:
template <std::size_t Idx, typename... Us>
auto& get_if_integral_impl (std::tuple<Us...>& t)
{
static_assert (Idx < std::tuple_size_v<std::tuple<Us...>>,
"No integral elements in this tuple.");
if constexpr (std::is_integral<std::tuple_element_t<Idx, std::tuple<Us...>>>::value)
return std::get<Idx> (t);
else
return get_if_integral_impl<Idx + 1> (t);
}
template<typename... Us>
auto& get_if_integral (std::tuple<Us...>& t)
{
return get_if_integral_impl<0> (t);
}
auto tup = std::make_tuple (3.f, 2., 1, 0);
std::cout << get_if_integral (tup); // '1'
My use case is a little more complex, involving returning the first nested tuple which itself contains another type, but this should convey the basic idea.
I have a class like this:
template<typename ... TTypes>
class Composite {
public:
std::tuple<TTypes...> &getRefValues() { return values; }
private:
std::tuple<TTypes...> values;
};
Can I define std::get for my class Composite? It should basically call the already defined std::get for the private tuple values.
I was able to implement a customized get function when the return type is known (e.g. for an int array member) but I don't know how to realize get when the return type can be an arbitrary type (depending on the components' type of the tuple values)?
You may do:
template <std::size_t I, typename... Ts>
auto get(Composite<Ts...>& composite)
-> decltype(std::get<I>(composite.getRefValues()))
{
return std::get<I>(composite.getRefValues());
}
Note: In C++14, you may omit the -> decltype(..) part.
For completeness, here is my solution. Thanks everyone:
template<typename ... TTypes>
class Composite {
public:
Composite(TTypes... t) {
std::tuple<TTypes...> tuple(t...);
values = tuple;
}
std::tuple<TTypes...> &getRefValues() { return values; }
private:
std::tuple<TTypes...> values;
};
namespace std {
template<size_t I, typename ... TTypes>
auto get(Composite<TTypes ...> &t) -> typename std::tuple_element<I, std::tuple<TTypes...>>::type {
return std::get<I>(t.getRefValues());
}
}
int main() {
Composite<int, char, double> c(13, 'c', 13.5);
std::cout << std::get<0>(c) << std::endl;
std::cout << std::get<1>(c) << std::endl;
std::cout << std::get<2>(c) << std::endl;
return 0;
}
I have a template class where each template argument stands for one type of value the internal computation can handle. Templates (instead of function overloading) are needed because the values are passed as boost::any and their types are not clear before runtime.
To properly cast to the correct types, I would like to have a member list for each variadic argument type, something like this:
template<typename ...AcceptedTypes> // e.g. MyClass<T1, T2>
class MyClass {
std::vector<T1> m_argumentsOfType1;
std::vector<T2> m_argumentsOfType2; // ...
};
Or alternatively, I'd like to store the template argument types in a list, as to do some RTTI magic with it (?). But how to save them in a std::initializer_list member is also unclear to me.
Thanks for any help!
As you have already been hinted, the best way is to use a tuple:
template<typename ...AcceptedTypes> // e.g. MyClass<T1, T2>
class MyClass {
std::tuple<std::vector<AcceptedTypes>...> vectors;
};
This is the only way to multiply the "fields" because you cannot magically make it spell up the field names. Another important thing may be to get some named access to them. I guess that what you're trying to achieve is to have multiple vectors with unique types, so you can have the following facility to "search" for the correct vector by its value type:
template <class T1, class T2>
struct SameType
{
static const bool value = false;
};
template<class T>
struct SameType<T, T>
{
static const bool value = true;
};
template <typename... Types>
class MyClass
{
public:
typedef std::tuple<vector<Types>...> vtype;
vtype vectors;
template<int N, typename T>
struct VectorOfType: SameType<T,
typename std::tuple_element<N, vtype>::type::value_type>
{ };
template <int N, class T, class Tuple,
bool Match = false> // this =false is only for clarity
struct MatchingField
{
static vector<T>& get(Tuple& tp)
{
// The "non-matching" version
return MatchingField<N+1, T, Tuple,
VectorOfType<N+1, T>::value>::get(tp);
}
};
template <int N, class T, class Tuple>
struct MatchingField<N, T, Tuple, true>
{
static vector<T>& get(Tuple& tp)
{
return std::get<N>(tp);
}
};
template <typename T>
vector<T>& access()
{
return MatchingField<0, T, vtype,
VectorOfType<0, T>::value>::get(vectors);
}
};
Here is the testcase so you can try it out:
int main( int argc, char** argv )
{
int twelf = 12.5;
typedef reference_wrapper<int> rint;
MyClass<float, rint> mc;
vector<rint>& i = mc.access<rint>();
i.push_back(twelf);
mc.access<float>().push_back(10.5);
cout << "Test:\n";
cout << "floats: " << mc.access<float>()[0] << endl;
cout << "ints: " << mc.access<rint>()[0] << endl;
//mc.access<double>();
return 0;
}
If you use any type that is not in the list of types you passed to specialize MyClass (see this commented-out access for double), you'll get a compile error, not too readable, but gcc at least points the correct place that has caused the problem and at least such an error message suggests the correct cause of the problem - here, for example, if you tried to do mc.access<double>():
error: ‘value’ is not a member of ‘MyClass<float, int>::VectorOfType<2, double>’
An alternate solution that doesn't use tuples is to use CRTP to create a class hierarchy where each base class is a specialization for one of the types:
#include <iostream>
#include <string>
template<class L, class... R> class My_class;
template<class L>
class My_class<L>
{
public:
protected:
L get()
{
return val;
}
void set(const L new_val)
{
val = new_val;
}
private:
L val;
};
template<class L, class... R>
class My_class : public My_class<L>, public My_class<R...>
{
public:
template<class T>
T Get()
{
return this->My_class<T>::get();
}
template<class T>
void Set(const T new_val)
{
this->My_class<T>::set(new_val);
}
};
int main(int, char**)
{
My_class<int, double, std::string> c;
c.Set<int>(4);
c.Set<double>(12.5);
c.Set<std::string>("Hello World");
std::cout << "int: " << c.Get<int>() << "\n";
std::cout << "double: " << c.Get<double>() << "\n";
std::cout << "string: " << c.Get<std::string>() << std::endl;
return 0;
}
One way to do such a thing, as mentioned in πάντα-ῥεῖ's comment is to use a tuple. What he didn't explain (probably to save you from yourself) is how that might look.
Here is an example:
using namespace std;
// define the abomination
template<typename...Types>
struct thing
{
thing(std::vector<Types>... args)
: _x { std::move(args)... }
{}
void print()
{
do_print_vectors(std::index_sequence_for<Types...>());
}
private:
template<std::size_t... Is>
void do_print_vectors(std::index_sequence<Is...>)
{
using swallow = int[];
(void)swallow{0, (print_one(std::get<Is>(_x)), 0)...};
}
template<class Vector>
void print_one(const Vector& v)
{
copy(begin(v), end(v), ostream_iterator<typename Vector::value_type>(cout, ","));
cout << endl;
}
private:
tuple<std::vector<Types>...> _x;
};
// test it
BOOST_AUTO_TEST_CASE(play_tuples)
{
thing<int, double, string> t {
{ 1, 2, 3, },
{ 1.1, 2.2, 3.3 },
{ "one"s, "two"s, "three"s }
};
t.print();
}
expected output:
1,2,3,
1.1,2.2,3.3,
one,two,three,
There is a proposal to allow this kind of expansion, with the intuitive syntax: P1858R1 Generalized pack declaration and usage. You can also initialize the members and access them by index. You can even support structured bindings by writing using... tuple_element = /*...*/:
template <typename... Ts>
class MyClass {
std::vector<Ts>... elems;
public:
using... tuple_element = std::vector<Ts>;
MyClass() = default;
explicit MyClass(std::vector<Ts>... args) noexcept
: elems(std::move(args))...
{
}
template <std::size_t I>
requires I < sizeof...(Ts)
auto& get() noexcept
{
return elems...[I];
}
template <std::size_t I>
requires I < sizeof...(Ts)
const auto& get() const
{
return elems...[I];
}
// ...
};
Then the class can be used like this:
using Vecs = MyClass<int, double>;
Vecs vecs{};
vecs.[0].resize(3, 42);
std::array<double, 4> arr{1.0, 2.0, 4.0, 8.0};
vecs.[1] = {arr.[:]};
// print the elements
// note the use of vecs.[:] and Vecs::[:]
(std::copy(vecs.[:].begin(), vecs.[:].end(),
std::ostream_iterator<Vecs::[:]>{std::cout, ' '},
std::cout << '\n'), ...);
Here is a less than perfectly efficient implementation using boost::variant:
template<typename ... Ts>
using variant_vector = boost::variant< std::vector<Ts>... >;
template<typename ...Ts>
struct MyClass {
using var_vec = variant_vector<Ts...>;
std::array<var_vec, sizeof...(Ts)> vecs;
};
we create a variant-vector that can hold one of a list of types in it. You have to use boost::variant to get at the contents (which means knowing the type of the contents, or writing a visitor).
We then store an array of these variant vectors, one per type.
Now, if your class only ever holds one type of data, you can do away with the array, and just have one member of type var_vec.
I cannot see why you'd want one vector of each type. I could see wanting a vector where each element is one of any type. That would be a vector<variant<Ts...>>, as opposed to the above variant<vector<Ts>...>.
variant<Ts...> is the boost union-with-type. any is the boost smart-void*. optional is the boost there-or-not.
template<class...Ts>
boost::optional<boost::variant<Ts...>> to_variant( boost::any );
may be a useful function, that takes an any and tries to convert it to any of the Ts... types in the variant, and returns it if it succeeds (and returns an empty optional if not).