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;
};

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.