Skip to content

Instantly share code, notes, and snippets.

@bzar
Created December 11, 2014 18:45
Show Gist options
  • Save bzar/406cddabeff450e988cb to your computer and use it in GitHub Desktop.
Save bzar/406cddabeff450e988cb to your computer and use it in GitHub Desktop.
A tuple of containers with compile-time seek by type in C++
#include <iostream>
#include <vector>
#include <type_traits>
template<template<typename...> class Container, typename T, typename... Ts>
class ContainerTuple
{
public:
template<typename TT>
typename std::enable_if<std::is_same<T, TT>::value, Container<T>&>::type get()
{
return container;
}
template<typename TT>
typename std::enable_if<std::__not_<std::is_same<T, TT>>::value, Container<TT>&>::type get()
{
return rest.get<TT>();
}
private:
Container<T> container;
ContainerTuple<Container, Ts...> rest;
};
template<template<typename...> class Container, typename T>
class ContainerTuple<Container, T>
{
public:
template<typename TT>
typename std::enable_if<std::is_same<T, TT>::value, Container<T>&>::type get()
{
return container;
}
private:
Container<T> container;
};
int main()
{
ContainerTuple<std::vector, int, bool, char> ct;
ct.get<int>().push_back(10);
ct.get<char>().push_back('y');
ct.get<char>().push_back('a');
ct.get<char>().push_back('y');
ct.get<char>().push_back('!');
ct.get<bool>().push_back(true);
std::cout << "expected: 10" << std::endl;
for(int const& i : ct.get<int>())
{
std::cout << i;
}
std::cout << std::endl;
std::cout << "expected: yay!" << std::endl;
for(char const& c : ct.get<char>())
{
std::cout << c;
}
std::cout << std::endl;
std::cout << "expected: true" << std::endl;
for(bool const& b : ct.get<bool>())
{
std::cout << b;
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment