Lets say we have a class TestClass
, which provide a move constructor and a move assignment operator.
class TestClass {
int data;
public:
TestClass() : data(0) {}
TestClass(TestClass const & other) = delete;
TestClass& operator=(TestClass const & other) = delete;
TestClass(TestClass&& other) : data(other.data) {
}
TestClass& operator=(TestClass&& other) {
data = other.data;
return *this;
}
};
We want encapsulate it with a macro, such that user can call the macro to create an instance, such as
#define TESTCLASS() TestClass()
auto instance = TESTCLASS();
This works well, except that each time user must declare a instance
variable to hold the instance. if the user write
TESTCLASS();
only a temporary instance will be created and died immediately.
In case of the user might forget to declare the instance variable, I would prefer that the macro with a temporary variable to hold the instance.
#define TESTCLASS_HOLDER() \
TEMPORARY_HOLDER_IN(CONCAT(TEMP_, __LINE__))
#define CONCAT(A, B) CONCAT_IMPL__(A, B)
#define CONCAT_IMPL__(A, B) A ## B
#define TEMPORARY_HOLDER_IN(tempoary) auto tempoary = TestClass()
By this way, we can hold the instance to a temporary variable.
TESTCLASS_HOLDER();
However, as this variable is temporary, user can not refer to it. What we need is a macro like TESTCLASS_HOLDER()
, but be able to std::move
the instance if user declares some other variable.
NEW_TESTCLASS_HOLDER(); // let this works together with the next line if any.
auto mytestclass = NEW_TESTCLASS_HOLDER(); //kind of chain assignment?
The problem is how to write such a macro NEW_TESTCLASS_HOLDER()
?