Type traits to get result of promotion from operator
关于此的后续问题是否有仅使用 C++98 且不提升的好方法?
最佳答案
只要你只需要担心标准的内置类型,你就可以这样做:
template <int> struct plus_helper;
template <> struct plus_helper< 1> { typedef char type; };
template <> struct plus_helper< 2> { typedef signed char type; };
template <> struct plus_helper< 3> { typedef unsigned char type; };
template <> struct plus_helper< 4> { typedef short type; };
template <> struct plus_helper< 5> { typedef unsigned short type; };
template <> struct plus_helper< 6> { typedef int type; };
template <> struct plus_helper< 7> { typedef unsigned int type; };
template <> struct plus_helper< 8> { typedef long type; };
template <> struct plus_helper< 9> { typedef unsigned long type; };
template <> struct plus_helper<10> { typedef float type; };
template <> struct plus_helper<11> { typedef double type; };
template <> struct plus_helper<12> { typedef long double type; };
template <> struct plus_helper<13> { typedef wchar_t type; };
template <typename T1, typename T2>
struct plus {
private:
static char (&f(char))[1];
static char (&f(signed char))[2];
static char (&f(unsigned char))[3];
static char (&f(short))[4];
static char (&f(unsigned short))[5];
static char (&f(int))[6];
static char (&f(unsigned int))[7];
static char (&f(long))[8];
static char (&f(unsigned long))[9];
static char (&f(float))[10];
static char (&f(double))[11];
static char (&f(long double))[12];
static char (&f(wchar_t))[13];
public:
typedef typename plus_helper<sizeof(f(*(T1*)0 + *(T2*)0))>::type type;
};
template <typename T1, typename T2>
struct plus<T1 *, T2> {
typedef T1 *type;
};
template <typename T1, typename T2>
struct plus<T1, T2 *> {
typedef T2 *type;
};
请注意,我要求可以添加 T1
和 T2
。如果不能,则不一定给出错误。另请注意,我没有省略短于 int
的类型。它们永远不会由内置的 +
运算符返回,但它们是自定义 operator+
的有效返回类型。
不幸的是,如果您还需要担心其他类型,例如自定义结构,这种方法将行不通,虽然我很乐意被证明是错误的,但我认为不可能做到这一点工作。
关于C++98 从运算符获取提升结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23085848/