A small C++ library for implementing collections suitable for use in high-level object-oriented APIs. The C++ iterators are a chore to implement and represent collections with a low-level, pointer-like abstraction. The proposed C++ range concept is much closer to what is needed in modern APIs. This library is a separate implementation of this concept focused on API readability and ease of implementation.
Add the simply.collections NuGet package to your Visual C++ project using the Package Manager Dialog or the Package Manager Console.
Install-Package simply.collections
Include the library header and use its namespace.
#include <simply/collections.h>
using namespace simply;
Implement an enumerable
, an internal class encapsulating a collection and responsible for creating enumerators.
#using <memory>
class answer_enumerable : public enumerable<int>
{
std::vector<int> answers { 40, 41, 42 };
public:
std::unique_ptr<enumerator<int>> create_enumerator() override
{
return std::make_unique<answer_enumerator>(answers);
}
};
Implement an enumerator
, an internal class responsible for returning elements of the collection, one by one.
#using <vector>
class answer_enumerator : public enumerator<int>
{
const std::vector<int> answers;
size_t index = 0;
public:
answer_enumerator(const std::vector<int> answers) : answers(answers)
{
}
bool get_next(int* element) override
{
if (index < answers.size())
{
*element = answers[index++];
return true;
}
return false;
}
};
Use the range
class to expose the collection in your API. Internally, it relies on the
enumerable
and enumerator
to implement begin
and end
iterators.
#using <memory>
class question
{
public:
range<int> answers()
{
return range<int> { std::make_shared<answer_enumerable>() };
}
};
You can use range
with the C++ 11 for
loop, the STL algorithms or any other code expecting C++ iterators.
#include <iostream>
#include <algorithm>
question q;
range<int> answers { q.answers() };
for (int answer : answers)
std::cout << answer;
std::for_each(std::begin(answers), std::end(answers), [](int answer) {
std::cout << answer;
});
This repository contains submodules.
git clone --recursive https://github.com/olegsych/simply.collections.git
From Visual Studio 2017:
- Open
simply.collections.sln
- Select Build Solution from the Build menu
- To switch build between
x86
andx64
platforms, select Configuration Manager from the Build menu and change the Active Solution Configuration
From Developer Command Prompt for VS2017:
msbuild simply.collections.sln /p:Platform=x86
msbuild simply.collections.sln /p:Platform=x64
From Visual Studio 2017:
- Select Run / All Tests from the Test menu
- To switch test execution between
x86
andx64
platform, select Test Settings from the Test menu and change the Default Processor Architecture.
From Developer Command Prompt for VS2017:
vstest.console bin\Win32\test.dll /Platform:x86
vstest.console bin\x64\test.dll /Platform:x64 /inIsolation