Genişletilmiş bir birleştirme desteği eklemek için bir yardımcı başlık dosyası oluşturdum.
Aşağıdaki kodu genel başlık dosyanıza eklemeniz ve gerektiğinde eklemeniz yeterlidir.
Kullanım Örnekleri:
ostream&
map_numbers(ostream& os, const void* payload, generic_primitive data)
{
static string names[] = {"Zero", "One", "Two", "Three", "Four"};
os << names[data.as_int];
const string* post = reinterpret_cast<const string*>(payload);
if (post) {
os << " " << *post;
}
return os;
}
int main() {
int arr[] = {0,1,2,3,4};
vector<int> vec(arr, arr + 5);
cout << vec << endl;
cout << join(vec.begin(), vec.end()) << endl;
cout << join(vec.begin(), vec.begin() + 2) << endl;
cout << join(vec.begin(), vec.end(), ", ") << endl;
cout << join(vec.begin(), vec.end(), ", ", map_numbers) << endl;
string post = "Mississippi";
cout << join(vec.begin() + 1, vec.end(), ", ", map_numbers, &post) << endl;
return 0;
}
Sahnenin arkasındaki kod:
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <unordered_set>
using namespace std;
#define GENERIC_PRIMITIVE_CLASS_BUILDER(T) generic_primitive(const T& v) { value.as_##T = v; }
#define GENERIC_PRIMITIVE_TYPE_BUILDER(T) T as_##T;
typedef void* ptr;
struct generic_primitive {
GENERIC_PRIMITIVE_CLASS_BUILDER(int);
GENERIC_PRIMITIVE_CLASS_BUILDER(ptr);
union {
GENERIC_PRIMITIVE_TYPE_BUILDER(int);
GENERIC_PRIMITIVE_TYPE_BUILDER(ptr);
};
};
typedef ostream& (*mapping_funct_t)(ostream&, const void*, generic_primitive);
template<typename T>
class Join {
public:
Join(const T& begin, const T& end,
const string& separator = " ",
mapping_funct_t mapping = 0,
const void* payload = 0):
m_begin(begin),
m_end(end),
m_separator(separator),
m_mapping(mapping),
m_payload(payload) {}
ostream&
apply(ostream& os) const
{
T begin = m_begin;
T end = m_end;
if (begin != end)
if (m_mapping) {
m_mapping(os, m_payload, *begin++);
} else {
os << *begin++;
}
while (begin != end) {
os << m_separator;
if (m_mapping) {
m_mapping(os, m_payload, *begin++);
} else {
os << *begin++;
}
}
return os;
}
private:
const T& m_begin;
const T& m_end;
const string m_separator;
const mapping_funct_t m_mapping;
const void* m_payload;
};
template <typename T>
Join<T>
join(const T& begin, const T& end,
const string& separator = " ",
ostream& (*mapping)(ostream&, const void*, generic_primitive) = 0,
const void* payload = 0)
{
return Join<T>(begin, end, separator, mapping, payload);
}
template<typename T>
ostream&
operator<<(ostream& os, const vector<T>& vec) {
return join(vec.begin(), vec.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const list<T>& lst) {
return join(lst.begin(), lst.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const set<T>& s) {
return join(s.begin(), s.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const Join<T>& vec) {
return vec.apply(os);
}