Skip to content

Instantly share code, notes, and snippets.

@simonrenger
Created March 10, 2019 21:25
Show Gist options
  • Save simonrenger/e3a36a42ee5c75ca6839ce3909ecb79b to your computer and use it in GitHub Desktop.
Save simonrenger/e3a36a42ee5c75ca6839ce3909ecb79b to your computer and use it in GitHub Desktop.
chained allocator based on Variadic templates
#include <tuple>
//#include "memory/Allocator.h"
struct Blk
{
void* ptr;
std::size_t size;
};
template<typename ...Args>
class Alloc : public Args...
{
template <std::size_t N>
using type = typename std::tuple_element<N, std::tuple<typename std::remove_reference<Args>::type...>>::type;
public:
template<std::size_t I = 0>
typename std::enable_if<I == sizeof...(Args), Blk>::type
test()
{
return { nullptr,0 };
}
template<std::size_t I = 0>
typename std::enable_if < I < sizeof...(Args), Blk>::type
test()
{
auto blk = type<I>::alloc();
if (blk.ptr == nullptr) {
return test<I + 1>();
}
return blk;
}
Blk alloc()
{
return test();
}
};
class A
{
protected:
Blk alloc()
{
std::cout << "Alloc A()\n";
return { nullptr,77 };
}
};
class C
{
protected:
Blk alloc()
{
std::cout << "Alloc C()\n";
return { nullptr,77 };
}
};
class B
{
protected:
Blk alloc()
{
std::cout << "Alloc B()\n";
return { new int(),77 };
}
};
template<typename T>
class Test
{
public:
using T::alloc;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment