use*_*759 5 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...
Run Code Online (Sandbox Code Playgroud)
他们必须做同样的事情...(除了我应该考虑到不同的大小),主要的想法是"如果类型是最广泛使用任务的代码...否则执行转换和执行代码".是否可以通过仅使用一种方法来避免所有这样的重复代码?(我只是不希望编译器在编译时给我一些警告......).
谢谢
这适用于所有整数类型:
template<
typename T,
typename = std::enable_if_t<std::is_integral<T>::value>
>
type& operator= (T);
Run Code Online (Sandbox Code Playgroud)
如果您想要依赖尺寸,可以简单地获得sizeof(T).您可以将其与您想要的最大尺寸进行比较.
如果你想要两个独立的函数,你需要将该子句放入其中并使用某种static-all.
除了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;
}
};
Run Code Online (Sandbox Code Playgroud)