C++模板自动类型升级
C++ template automatic type promotion
template <class T>
class Foo {
public:
T val;
Foo(T _v): val(_v){}
friend ostream& operator<< (ostream& out, const Foo& A) {
out << A.val;
return out;
}
};
template <class X, class Y> Foo<???> operator+(const Foo<X>& A, const Foo<Y> & B) {
if (sizeof(X) > sizeof (Y))
return Foo<X>(A.val + B.val);
else
return Foo<Y>(A.val + B.val);
}
int main() {
Foo<double> a(1.5);
Foo<int> b(2);
cout << a << endl;
cout << b << endl;
cout << a+b << endl;
}
我的目标是让 operator+
函数根据参数的类型返回不同的类型。
例如,如果 a
int
并且 b int
则返回 Foo<int>
,如果其中一个或两个都double
则返回 Foo<double>
。
可以做到吗?
(C++11(:在dectype中使用declval
表达式:
#include <utility>
template <class X, class Y>
Foo<decltype(std::declval<X>() + std::declval<Y>())> operator+(...);
使用部分模板专用化可以(在 C++03 或 C++11 中(做到这一点。
// C++ does not allow partial specialization of function templates,
// so we're using a class template here.
template <typename X, typename Y, bool xLarger>
struct DoPlusImpl // When x is selected
{
typedef Foo<X> result_type;
};
template <typename X, typename Y>
struct DoPlusImpl<X, Y, false> // When y is selected
{
typedef Foo<Y> result_type;
};
template <typename X, typename Y> // Select X or Y based on their size.
struct DoPlus : public DoPlusImpl<X, Y, (sizeof (X) > sizeof (Y))>
{};
// Use template metafunction "DoPlus" to figure out what the type should be.
// (Note no runtime check of sizes, even in nonoptimized builds!)
template <class X, class Y>
typename DoPlus<X, Y>::result_type operator+(const Foo<X>& A, const Foo<Y> & B) {
return typename DoPlus<X, Y>::result_type
(A.val + B.val);
}
您可以在 IDE 上看到此操作 此处 -> http://ideone.com/5YE3dg
是的
!如果您想给出自己的规则,请按以下方法:
template <typename X, typename Y> struct Rule {};
template<> struct Rule<int, int> { typedef int type;};
template<> struct Rule<float, int> { typedef bool type;};
然后
template <class X, class Y> Foo<typename Rule<X, Y>::type> operator+(...)
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型