Type Traits: Compile-Time Type Analysis

Creating a Custom Type Trait to Check for a Member Function

How can I create a custom type trait to check if a type has a specific member function?

Illustration representing computer hardware

To create a custom type trait that checks for the presence of a specific member function in a type, you can use SFINAE (Substitution Failure Is Not An Error) techniques. Here's an example of how to create a type trait has_render that checks if a type has a Render member function:

#include <iostream>
#include <type_traits>

// Helper struct for SFINAE
template <typename T>
struct has_render {
  template <typename U>
  static auto test(U* p)
    -> decltype(p->Render(), std::true_type{});

  template <typename>
  static std::false_type test(...);

  static constexpr bool value =
    decltype(test<T>(nullptr))::value;
};

// _v version for convenience
template <typename T>
inline constexpr bool has_render_v =
  has_render<T>::value;

// Example classes
class WithRender {
 public:
  void Render() {}
};

class WithoutRender {};

int main() {
  std::cout << std::boolalpha;
  std::cout << "WithRender has Render: "
    << has_render_v<WithRender> << "\n";
  std::cout << "WithoutRender has Render: "
    << has_render_v<WithoutRender> << "\n";
}
WithRender has Render: true
WithoutRender has Render: false

In this example, the has_render struct uses SFINAE to detect the presence of a Render member function. The test function is overloaded based on whether Render can be called on a pointer to the type T. If Render is present, the first overload is selected, and std::true_type is returned. Otherwise, the second overload is selected, and std::false_type is returned.

The has_render_v variable template is provided for convenience, similar to the _v suffix used in standard library type traits.

This technique can be adapted to check for the presence of other member functions or member variables in a type.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved