Skip to content

Instantly share code, notes, and snippets.

@khvorov
Created November 29, 2014 07:27
Show Gist options
  • Save khvorov/579d3064dc3255f2a0b0 to your computer and use it in GitHub Desktop.
Save khvorov/579d3064dc3255f2a0b0 to your computer and use it in GitHub Desktop.
For a given tuple type constructs a new tuple where all element types are const
// $ clang++ -Wall -Wextra -pedantic -std=c++1y make_const_tuple.cpp -o /tmp/a.out
// make_const_tuple.cpp:43:22: error: read-only variable is not assignable
// std::get<0>(ctr) = 1;
// ~~~~~~~~~~~~~~~~ ^
// make_const_tuple.cpp:48:21: error: read-only variable is not assignable
// std::get<0>(ct) = 1;
// ~~~~~~~~~~~~~~~ ^
#include <tuple>
#include <type_traits>
// uncomment this code to use with C++11
// template <typename T>
// using Constify = typename std::conditional<
// std::is_reference<T>::value,
// typename std::add_lvalue_reference<
// typename std::add_const<
// typename std::remove_reference<T>::type
// >::type
// >::type,
// typename std::add_const<T>::type
// >::type;
template <typename T>
using Constify = std::conditional_t<
std::is_reference<T>::value,
std::add_lvalue_reference_t<std::add_const_t<std::remove_reference_t<T>>>,
std::add_const_t<T>>;
template <typename T>
struct make_const_tuple;
template <template <typename ...> class T, typename... Ts>
struct make_const_tuple<T<Ts...>>
{
typedef T<Constify<Ts>...> type;
};
template <typename T> using const_tuple = typename make_const_tuple<T>::type;
int main()
{
using tpl_ref = std::tuple<int &, double &>;
using tpl = std::tuple<int, double>;
int i = 0;
double d = 0.1;
// reference
tpl_ref tr = std::tie(i, d);
const_tuple<tpl_ref> ctr = tr;
std::get<0>(ctr) = 1;
// value
tpl t = std::make_tuple(i, d);
const_tuple<tpl> ct = t;
std::get<0>(ct) = 1;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment