Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
c++

What are traits in C/C++?

Behzad Ahmad

Traits allow us to learn more information about a type. Using traits, an algorithm can change how it works depending on specific object traits, such as functions and variables.

Traits are written in the form of a templated struct. They represent a set of methods that extend the functionality of a class.

overview of how traits work
#include <iostream>
#include <limits>
using namespace std;

template <typename T>
T minimum(const T* data, int size) 
{
  T temp = numeric_limits<T>::min();

  for (int i=0; i < size; i++)
  {
    if (data[i] > temp)
      temp = data[i];

    return temp;
  }
} 

int main() 
{

  unsigned int ptr1[] = {1,3,2};
  cout << minimum(ptr1,3) << endl;

  float ptr2[] = {4.1,4.3,4.2};
  cout << minimum(ptr2,3) << endl;
}
C++ implementation of traits

In the code above, we find the minimum value from different types of arrays:

Using the traits class, numeric_limits, the type becomes part of the name, and the minimum value for a type float becomes numeric_limits<float>::min(). With this, we don’t really need to remember which type we need to use. We also have a function that finds the minimum value by holding a value that checks if the next value is smaller. If the next value is smaller than the first value, then we store that value and check the other values with that stored value. In this way, we can find the minimum value.

RELATED TAGS

c
c++

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring