CPP Type¶
The CPPType
class (source) allows working with arbitrary C++ types in a generic way. An instance of CPPType
wraps exactly one type like int
or std::string
.
CPPType
is mostly concerned with properly constructing, destructing, copying and moving types, instead of doing more type specific operations (like addition). As such, it can be used to implement containers whose data type is only known at run-time like GArray
and GSpan
(where G means "generic").
Typically, performance sensitive sections are still implemented in specialized and often templated code. However, the higher level "data logistics" (getting the right data to the right place) can be implemented generically without the need for templates.
/* A generic swap implementation that works with all types which have a CPPType. */
void generic_swap(void *a, void *b, const CPPType &type) {
BUFFER_FOR_CPP_TYPE_VALUE(type, buffer)
type.move_construct(a, buffer);
type.move_assign(b, a);
type.move_assign(buffer, b);
type.destruct(buffer);
}
/* Initialize values. */
std::string a = "A";
std::string b = "B";
/* Get the CPPType for std::string. */
/* This only works when BLI_CPP_TYPE_MAKE was used for the type. */
const CPPType &type = CPPType::get<std::string>();
/* Swap values in a and b. */
generic_swap(&a, &b, type);