Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Elegant way to implement assignment of different type using one method and without warning?

I have to implement basically the same function but for different size. Specifically it is something like...

type& operator=(unsigned int);
type& operator=(unsigned long int);
type& operator=(unsigned long long int);
type& operator=(int);
type& operator=(long int);
type& operator=(long long int);
type& operator=(short int);
//so on and so forth...

They have to do exactly the same thing... (except i should take into account the different size), the main idea would be "if the type is the widest use the code for the task... otherwise perform a casting and execute the code". Is it possible to avoid all such repetitive code by using only one method? (i just don't want the compiler throw me some warning when i compile...).

Thank you

like image 763
user8469759 Avatar asked Sep 23 '15 10:09

user8469759


1 Answers

This will work for all integral types:

template<
    typename T,
    typename = std::enable_if_t<std::is_integral<T>::value>
>
type& operator= (T);

If you want to depend on size, it can be obtained with simply sizeof(T). You can compare that with your biggest desired size.

If you wanted two separate functions, you'd need to put that clause in as well and use some sort of static-all.

like image 82
Bartek Banachewicz Avatar answered Oct 01 '22 11:10

Bartek Banachewicz