Zebrafish
Zebrafish

Reputation: 13876

How can I pass a type or variable to this is_same function?

I want to be able to pass a type or variable to a function that will return true or false if it's the same type:

template <typename T>
struct OneType
{
    template <typename U> //???
    static constexpr bool is_same_type(U u = std::declval<U>()) { return std::is_same_v<T, U>; }
};

struct AnotherType
{
    AnotherType() = delete;
    AnotherType(int a) {}
};

void main()
{
    OneType<int> a;

    a.is_same_type<int>(); // CAN BE CALLED WITH A TYPE
    
    int anInt;
    a.is_same_type(anInt); // CAN BE CALLED WITH A VARIABLE

    
    AnotherType anotherType(7);
    a.is_same_type<AnotherType>(); // CAN THESE BE MADE TO WORK?
    a.is_same_type(anotherType); 

}

Upvotes: 2

Views: 421

Answers (1)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5222

The default value is unnecessary, just define:

template <typename U>
static constexpr bool is_same_type() { return std::is_same_v<T, U>; }

Then use it with parenthesis:

a.is_same_type<AnotherType>();

If the type of an object is needed then decltype can be used:

AnotherType obj;
a.is_same_type<decltype(obj)>();

Upvotes: 6

Related Questions