Adrian McCarthy
Adrian McCarthy

Reputation: 47954

Constraining template parameters

Suppose I have a class template, Angle<T>, and I want to constrain instantiation to Ts that are floating point types.

The SFINAE approach:

template <typename T,
          std::enable_if_t<std::is_floating_point_v<T>, bool> = true>
struct Angle { T m_radians; };

C++20 gives us concepts:

template <std::floating_point T>
struct Angle { T m_radians; };

Alternatively, I could constrain the type with static_assert:

template <typename T>
struct Angle {
    static_assert(std::is_floating_point_v<T>,
                  "Angle<T> works only with floating point types.");
    T m_radians;
};

Question: Are there constraints I could place on template parameters with concepts/requires that I couldn't do with <type_traits>/static_assert?

[I'm not asking for opinions about which technique is better. Also, I understand that concepts, like enable_if, can leverage SFINAE to eliminate overloads and specializations from consideration during resolution, which you cannot do with static_assert. My question is strictly about constraints.]

Upvotes: 0

Views: 95

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275340

They are all capable of doing Turing-complete computation on the passed in types and accepting an arbitrary subset, and have access to the same information about each type.

None is stronger or weaker.

Upvotes: 1

Related Questions