Created
June 19, 2017 07:15
-
-
Save x100ex/5db76bc574c49087a60342afd62640dd to your computer and use it in GitHub Desktop.
мутабельная копия константного объекта
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (C) 2017, Aleksander A. Popov. | |
// | |
// Создание копии константного объекта при необходимости использования | |
// ссылки или указателя на мутабельный объект | |
// | |
template <typename T> | |
class CreateMutCopy { | |
T copy_; | |
public: | |
T& operator()(const T& t) { | |
copy_ = t; | |
return ©_; | |
} | |
CreateMutCopy& operator<<(const T& t) { | |
copy_ = t; | |
return *this; | |
} | |
operator T&() { return copy_; } | |
operator T*() { return ©_; } | |
}; | |
// 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