使用 decltype 的条件声明类型
conditional declaration of type using decltype
我认为条件类型可以在模板函数中使用decltype
来声明。但似乎不是。谁能指出我的测试代码有什么问题?
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
#define print_type(var) do {
std::cout << type_id_with_cvr<decltype(var)>().pretty_name() << std::endl;
} while(0)
template <typename T1, typename T2>
auto max(T1 a, T2 b) -> decltype(a < b ? b : a) {
decltype(a < b ? b : a) c = a < b ? b : a;
print_type(c);
return a < b ? b : a;
}
int main() {
int i = 10;
double d = 3.3;
decltype(i < d? d : i) r = i < d? d : i;
print_type(r); // -> double
std::cout << r << std::endl; // 10
}
我想你的意图
decltype( a < b ? a : b )
是获得b
类型时a < b
,否则获得a
类型。
也就是说:我想您的意图是根据a
和b
的运行时间值获得类型确定的运行时间。
这在C++是不可能的,因为变量的类型必须在编译时决定。
有了这个decltype()
你得到三元运算符的类型
a < b ? a : b
这不依赖于a
和b
的值,而仅取决于它们的类型。
所以,在这种情况下
decltype(i < d? d : i)
其中i
是int
,d
是double
,你得到一个double
,i
和d
的值无关紧要。
相关文章:
- std::enable_if 更改成员 *变量* 声明/类型
- 对前向声明类型进行unique_ptr的解决方法
- 如何将声明类型作为参数发送
- 在 Fortran 中泛化特定声明类型的操作
- 使用 (c++11) 声明类型时放置 __declspec(dllimport) 关键字的位置
- 模板函数可以使用带有删除的构造函数的声明类型
- 声明类型没有任何可变类型
- 如何使用声明类型简化此代码
- 使用声明类型选择函数专业化
- 替代班级内声明类型的别名
- 对于自动键入推论的参数,声明类型(自动)应推导的内容
- 使用 decltype 的条件声明类型
- 您如何声明类型结构的堆栈?在C 中
- 将指向前向声明类型的指针推送到 typedef'd 向量时出现编译器错误
- 声明适用于 auto,但不能显式声明类型?
- 声明类型包含未展开的参数包'Args'
- 课堂上的Typedef.在另一个类错误中:尚未声明类型
- 冲突的声明类型/价值不匹配
- 获取具有AST访问者clang的功能声明类型
- 变量声明类型定义 C 中的约定