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

时间:2015-09-23 10:30:57

标签: c++ polymorphism assignment-operator

我必须实现基本相同的功能,但是对于不同的大小。具体来说就是......

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

他们必须做同样的事情......(除了我应该考虑到不同的大小),主要的想法是“如果类型是最广泛的使用代码的任务...否则执行一个转换并执行代码“。是否可以通过仅使用一种方法来避免所有这样的重复代码? (我只是不希望编译器在编译时给我一些警告......)。

谢谢

2 个答案:

答案 0 :(得分:6)

这适用于所有整数类型:

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

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

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

答案 1 :(得分:6)

除了answer of Bartek Banachewicz另一种解决方法:

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