9/09/2025

Simple example code for remove_cvref.

 

Simple example code for remove_cvref

.

#include <iostream>
#include <type_traits>

// Simple implementation of remove_cvref_t (C++20 feature)
template<typename T>
struct remove_cvref {
using type = std::remove_cv_t<std::remove_reference_t<T>>;
};

template<typename T>
using remove_cvref_t = typename remove_cvref<T>::type;

// Helper to print type names
template<typename T>
void print_type_info(const char* original_type) {
std::cout << "Original: " << original_type << std::endl;
std::cout << "After remove_cvref_t: ";
// Check what type we have after removal
if (std::is_same_v<T, int>) {
std::cout << "int" << std::endl;
} else if (std::is_same_v<T, float>) {
std::cout << "float" << std::endl;
} else if (std::is_same_v<T, double>) {
std::cout << "double" << std::endl;
}
std::cout << "---" << std::endl;
}

// Example class
class MyClass_MareArts {
public:
int value;
};

int main() {
// Example 1: const int&
using Type1 = const int&;
using Clean1 = remove_cvref_t<Type1>;
print_type_info<Clean1>("const int&");
// Example 2: volatile float&&
using Type2 = volatile float&&;
using Clean2 = remove_cvref_t<Type2>;
print_type_info<Clean2>("volatile float&&");
// Example 3: const volatile double&
using Type3 = const volatile double&;
using Clean3 = remove_cvref_t<Type3>;
print_type_info<Clean3>("const volatile double&");
// Example 4: Plain int (no change)
using Type4 = int;
using Clean4 = remove_cvref_t<Type4>;
print_type_info<Clean4>("int");
// Practical example with templates
auto lambda = []<typename T>(T&& value) {
// T might be const MyClass&, MyClass&&, etc.
using CleanType = remove_cvref_t<T>;
// Now CleanType is always just MyClass
CleanType copy = value; // Can create a clean copy
copy.value = 42; // Can modify the copy
std::cout << "Modified copy value: " << copy.value << std::endl;
};
const MyClass_MareArts obj{10};
lambda(obj); // Pass const object
MyClass_MareArts obj2{20};
lambda(std::move(obj2)); // Pass rvalue
return 0;
}

..