Skip to content

Instantly share code, notes, and snippets.

@x100ex
Created June 19, 2017 07:15
Show Gist options
  • Save x100ex/5db76bc574c49087a60342afd62640dd to your computer and use it in GitHub Desktop.
Save x100ex/5db76bc574c49087a60342afd62640dd to your computer and use it in GitHub Desktop.
мутабельная копия константного объекта
// Copyright (C) 2017, Aleksander A. Popov.
//
// Создание копии константного объекта при необходимости использования
// ссылки или указателя на мутабельный объект
//
template <typename T>
class CreateMutCopy {
T copy_;
public:
T& operator()(const T& t) {
copy_ = t;
return &copy_;
}
CreateMutCopy& operator<<(const T& t) {
copy_ = t;
return *this;
}
operator T&() { return copy_; }
operator T*() { return &copy_; }
};
// usage example
void foo1(std::vector<int>& data_swapped) {}
void foo2(std::vector<int>* data_swapped) {}
void bar(const std::vector<int>& data) {
CreateMutCopy<std::vector<int> > cmc;
foo1(cmc << data);
foo1(cmc(data));
foo2(cmc << data);
foo2(&cmc(data));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment