Skip to content

Instantly share code, notes, and snippets.

@LucHermitte
Last active October 22, 2016 19:38
Show Gist options
  • Save LucHermitte/308a7dc8363f235e9a81 to your computer and use it in GitHub Desktop.
Save LucHermitte/308a7dc8363f235e9a81 to your computer and use it in GitHub Desktop.
Helper macro to delegate function calls to member functions from attributes
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// (c) 2015 Luc Hermitte
#include <vector>
#include <iostream>
#include <algorithm>
#include <list>
#define DELEGATE_TO(fname, attribute) \
auto fname() const noexcept(noexcept(attribute.fname())) { \
return attribute.fname(); \
}
// Will lead to cryptic message errors
#define DELEGATE_TO2(fname, attribute) \
template <typename... Args> \
auto fname(Args &&... args) const noexcept(noexcept(attribute.fname(args...))) { \
return attribute.fname(args...); \
}
template <typename T>
class sorted_vector final
{
public:
sorted_vector() = default;
sorted_vector(std::initializer_list<T> init)
: m_vector(init)
{
std::sort(m_vector.begin(),m_vector.end());
}
DELEGATE_TO(cbegin, m_vector);
DELEGATE_TO(cend , m_vector);
DELEGATE_TO(begin , m_vector);
DELEGATE_TO(end , m_vector);
DELEGATE_TO(size , m_vector);
DELEGATE_TO(back , m_vector);
// DELEGATE_TO(empty , m_vector);
DELEGATE_TO2(empty , m_vector);
DELEGATE_TO2(operator[], m_vector);
DELEGATE_TO2(swap, m_vector);
// using m_vector::swap; won't work :(
private:
std::vector<T> m_vector;
};
int main ()
{
sorted_vector<int> s = {1, 2, 3};
std::cout << std::boolalpha;
std::cout << s.back() << "\n";
std::cout << s.empty() << "\n";
std::cout << s[0] << "\n";
// std::cout << s["toto"];
}
// Vim: let $CXXFLAGS='-std=c++14'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment