C++ 使用一种方法且没有警告地实现不同类型赋值的优雅方法?

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

我必须实现基本相同的功能,但尺寸不同。具体来说,它类似于...

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...

他们必须做完全相同的事情...(除了我应该考虑到不同的大小),主要想法是 "if the type is the widest use the code for the task... otherwise perform a casting and execute the code"。是否可以仅使用一种方法来避免所有这些重复代码? (我只是不想让编译器在我编译时给我一些警告...)。

谢谢

这适用于所有整数类型:

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

如果你想依赖大小,只需sizeof(T)即可获得。您可以将其与您想要的最大尺寸进行比较。

如果您想要两个单独的函数,则需要将该子句也放入其中并使用某种静态全部。

除了另一种解决方法:

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;
    }
};