user3513346
user3513346

Reputation: 117

C++11 Type Traits: Arithmetic user type

Example:

struct IntWrapper { int x; operator int() const { return x; } ... }
static_assert(std::is_integral<IntWrapper>::value, "Invalid type.");

Is it possible to get std::is_integral<IntWrapper>::value to be true?

Thanks.

Upvotes: 1

Views: 192

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 219185

Is it possible to get std::is_integral<IntWrapper>::value to be true?

Yes, it is possible. But not without creating undefined behavior. I.e. when you try to do this, the resulting undefined behavior could be exactly what you want. Or it could be most anything you don't want. And testing won't help.

But all is not lost. You can easily create your own trait to do what exactly what you want. For example:

template <class T>
struct IsMyInt
    : std::is_integral<T>
{
};

template <>
struct IsMyInt<IntWrapper>
    : std::true_type
{
};

static_assert(IsMyInt<IntWrapper>::value, "Invalid type.");

IsMyInt behaves exactly as how you wished std::is_integral behaves, but without undefined behavior. So now all you have to do is use IsMyInt instead of std::is_integral.

Upvotes: 3

Related Questions