Bill
Bill

Reputation: 339

What is the c++ std library implementer's concern to warn the undefined behavior in adding specialization for remove_cvref template?

In this link, https://en.cppreference.com/w/cpp/types/remove_cvref, it states

template< class T >
struct remove_cvref;

If the type T is a reference type, provides the member typedef type which is the type referred to by T with its topmost cv-qualifiers removed. Otherwise type is T with its topmost cv-qualifiers removed.

The behavior of a program that adds specializations for remove_cvref is undefined.

What is the c++ std library implementer's concern in this case?

Upvotes: 0

Views: 136

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473926

The C++ standard forbids specializations of pretty much any of the C++ type traits templates. The reason to do that is because the type traits are supposed to be low-level, basic constructs that do exactly and only what they say. This means that users should not be allowed to pull the usual shenanigans with them by replacing their functionality with whatever they want.

Let's say that you're in a template function over some template parameter type T. And you want to execute some code conditionally if T happens to be an int. But this code would work just fine if T is an int& or a const int or whatever. You just want to see if the user provided an int as a type.

You use remove_cvref_t to get int as a type, then is_same_v it against int. This can only work if remove_cvref does exactly and only what it says it does. If a user can specialize it, then they can lie to you, making their user-defined type appear like an int and thereby break your code.

Think of type-traits in C++ as language type operations that are defined in a header rather than always being present. By all rights, C++ ought to have an operator that converts a type into the removed-cvref version of itself. Instead of a dedicated operator, we have type trait metafunctions. But regardless of how it gets defined, it is still a fundamental operation that you should not be able to change the meaning of.

Upvotes: 6

Related Questions