- Examples

The examples for application of type-traits in embedded programming.

Example 1

Here is the application of the primary type categories:

Press + to interact
// typeTraitsTypeCategories.cpp
#include <iostream>
#include <type_traits>
using namespace std;
int main(){
cout << endl;
cout << boolalpha;
cout << "is_void<void>::value: " << is_void<void>::value << endl;
cout << "is_integral<short>::value: " << is_integral<short>::value << endl;
cout << "is_floating_point<double>::value: " << is_floating_point<double>::value << endl;
cout << "is_array<int []>::value: " << is_array<int [] >::value << endl;
cout << "is_pointer<int*>::value: " << is_pointer<int*>::value << endl;
cout << "is_null_pointer<std::nullptr_t>::value: " << is_null_pointer<std::nullptr_t>::value << endl;
struct A{
int a;
int f(double){return 2011;}
};
cout << "is_member_object_pointer<int A::*>::value: " << is_member_object_pointer<int A::*>::value << endl;
cout << "is_member_function_pointer<int (A::*)(double)>::value: " << is_member_function_pointer<int (A::*)(double)>::value << endl;
enum E{
e = 1,
};
cout << "is_enum<E>::value: " << is_enum<E>::value << endl;
union U{
int u;
};
cout << "is_union<U>::value: " << is_union<U>::value << endl;
cout << "is_class<string>::value: " << is_class<string>::value << endl;
cout << "is_function<int * (double)>::value: " << is_function<int * (double)>::value << endl;
cout << "is_lvalue_reference<int&>::value: " << is_lvalue_reference<int&>::value << endl;
cout << "is_rvalue_reference<int&&>::value: " << is_rvalue_reference<int&&>::value << endl;
cout << endl;
}

Explanation

Due to the flag boolalpha in line 10, the program displays either true or false instead of 1 or 0. Each call of the 14 primary type categories returns true.

Example 2

Press + to interact
// typeTraitsCopy.cpp
#include <string.h>
#include <iostream>
#include <type_traits>
namespace my{
template<typename I1, typename I2, bool b>
I2 copy_imp(I1 first, I1 last, I2 out, const std::integral_constant<bool, b>&){
while(first != last){
*out = *first;
++out;
++first;
}
std::cout << "elementwise." << std::endl;
return out;
}
template<typename T>
T* copy_imp(const T* first, const T* last, T* out, const std::true_type&){
memcpy(out, first, (last-first)*sizeof(T));
std::cout << "bitwise." << std::endl;
return out+(last-first);
}
template<typename I1, typename I2>
I2 copy(I1 first, I1 last, I2 out){
typedef typename std::iterator_traits<I1>::value_type value_type;
return copy_imp(first, last, out, std::is_trivially_copy_assignable<value_type>());
}
}
const int arraySize = 1000;
// intialize all elements to 0
int intArray[arraySize] = {0, };
int intArray2[arraySize]={0, };
int* pArray = intArray;
const int* pArray2 = intArray2;
int main(){
std::cout << std::endl;
std::cout << "Copying pArray ";
my::copy(pArray2, pArray2 + arraySize, pArray);
std::cout << "\n" << "Copying intArray ";
my::copy(intArray2, intArray2 + arraySize, intArray);
}

Explanation

  • ...