Showing posts with label cpp_sfinae. Show all posts
Showing posts with label cpp_sfinae. Show all posts

May 10, 2023

[C++] SFINAE for testing type convertible

Reference:
https://en.cppreference.com/w/cpp/types/is_convertible
[C++][cppcon 2017] Write our own type trait

Use function parameter type to test if a incoming argument type is implicitly convertible to parameter type.

This trick can be used in SFINAE to test type convertibility.

#include <type_traits>

struct O2 {};
struct O1 {
  O1() = default;
  O1(const O2 &) {}
};

int main() {
  // cannot be converted:
  // decltype(void(std::declval<void (&)(O2)>()(std::declval<O1>()))) A;
  decltype(void(std::declval<void (&)(O1)>()(std::declval<O2>()))) *A = nullptr;
};

Jul 23, 2014

[C++] SFINAE trick with C++14 feature use

Compile time introspection in C++14 using single constexpr.

Nice use of tricks of sizeof, mentioned in Davide Di Gennaro's book:
Advanced C++ Metaprogramming with C++14 features enabled.

2 things to be noticed:

  1. decltype won't evaluate it's content. Which it can't take lambda expression as an argument.
  2. Lambdas can't be passed as parameters to constexpr functions. Ref: constexpr lambda functions

The technique is made use of
declval (std::add_rvalue_reference<T>::type)  / decltype / sizeof / template lambda / SFINAE