C ++ Elegant way to implement assignment of various types using one method and without warning?

I need to implement almost the same function, but for different sizes. In particular, 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 should do the same ... (except that I have to consider different sizes), the main idea would be that "if the type is the most extensive use of code for the task ... otherwise cast and execute code. " Is it possible to eliminate all such duplicate code using only one method? (I just don't want the compiler to give me a warning when compiling ...).

thanks

+5
source share
2 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, you can get it just sizeof(T) . You can compare this to your largest desired size.

If you need two separate functions, you also need to put this sentence and use some kind of static-all.

+6
source

In addition to Bartek Banachewicz's answer, an alternative way to solve it:

 struct type { ////Solution by Bartek Banachewicz //template<typename T,typename = typename std::enable_if<std::is_integral<T>::value>::type> //type& operator= (T) //{ // return *this; //} template<typename T> auto operator=(T) -> typename std::enable_if<std::is_integral<T>::value, type>::type& { return *this; } }; 
+6
source

Source: https://habr.com/ru/post/1232089/


All Articles