not-a-user
not-a-user

Reputation: 4327

Why can we have instances of type traits classes in C++?

#include <type_traits>

int main()
{
    std::decay<int()> p;
    static_assert(1 == sizeof(p));
    
    std::add_pointer<int> q;
    static_assert(1 == sizeof(q));
}

This is working. But why do we need instances of decay etc.? This makes typos (decay instead of decay_t etc.) harder to spot. Should these classes not have a private or deleted constructor?

Upvotes: 0

Views: 266

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

Why not? Sometimes it is necessary to create objects of traits and not allowing that would create problems for some without substantial benefit for the rest.

For example you can use traits for tag dispatch:

#include <type_traits>
#include <iostream>

void foo(std::false_type) {
    std::cout << "this is the overload for std::false_type";
}
void foo(std::true_type) {
    std::cout << "this is the overload for std::true_type";
}

int main() {
    foo( std::is_same<int,double>{} );
}

Neither caller nor the function actually use the object, but it has to be instantiated to pick the desired overload.

Upvotes: 4

eerorika
eerorika

Reputation: 238351

Why can we have instances of type traits classes in C++?

Because type traits are class templates and classes can be instantiated unless their constructors are deleted.

In fact, Cpp17UnaryTypeTrait and Cpp17BinaryTypeTrait are required / guaranteed to be Cpp17DefaultConstructible. Cpp17TransformationTrait appears to not have this requirement / guarantee.

Upvotes: 1

Related Questions