Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

integer conversion operator conditional on size of integer

27 views
Skip to first unread message

Daniel

unread,
Jul 18, 2018, 12:58:07 PM7/18/18
to
Consider

class A
{
int32_t value1_;
int64_t value2_;
public:
A() : value1_(10), value2_(20) {}

explicit operator int32_t() const
{
return value1_;
}

explicit operator int64_t() const
{
return value2_;
}
}

such that we can write

int main()
{
A a;

std::cout << (int32_t)a << ", " << (int64_t)a << std::endl;
}

and get the expected output

10, 20

The important feature in the problem statement is that a cast to an integer
of size sizeof(int32_t) gets a value one way, and a cast to an integer of
size sizeof(int64_t) gets it another way.

Now suppose we want to have this work for all integer types in a platform
independent way, e.g. we want

std::cout << (int)a << ", " << (long)a << ", " << (long long)a << std::endl;

to return 10 or 20 depending on the size of the integer, or not compile if
the integer type is not 32 or 64 bits.

I'm having some difficulty solving this with SFINAE. Any suggestions?

Thanks,
Daniel

Paavo Helde

unread,
Jul 18, 2018, 1:49:41 PM7/18/18
to
Something like this?

#include <iostream>

class A
{
int32_t value1_;
int64_t value2_;
private:
template<int sz> struct traits { using type = void; };
template<> struct traits<4> { using type = int32_t; };
template<> struct traits<8> { using type = int64_t; };

template<int sz> typename traits<sz>::type Get() const;
template<> traits<4>::type Get<4>() const { return value1_; }
template<> traits<8>::type Get<8>() const { return value2_; }

public:
A() : value1_(10), value2_(20) {}

template<typename T>
explicit operator T() const
{
return Get<sizeof(T)>();
}
};

Daniel

unread,
Jul 18, 2018, 7:19:28 PM7/18/18
to
On Wednesday, July 18, 2018 at 1:49:41 PM UTC-4, Paavo Helde wrote:

> Something like this?
>
> #include <iostream>
>
> class A
> {
> int32_t value1_;
> int64_t value2_;
> private:
> template<int sz> struct traits { using type = void; };
> template<> struct traits<4> { using type = int32_t; };
> template<> struct traits<8> { using type = int64_t; };
>
> template<int sz> typename traits<sz>::type Get() const;
> template<> traits<4>::type Get<4>() const { return value1_; }
> template<> traits<8>::type Get<8>() const { return value2_; }
>
> public:
> A() : value1_(10), value2_(20) {}
>
> template<typename T>
> explicit operator T() const
> {
> return Get<sizeof(T)>();
> }
> };
>
> int main()
> {
> A a;
>
> std::cout << (int32_t)a << ", " << (int64_t)a << std::endl;
> }

Thanks!
Daniel

0 new messages