c++ - 模板接受 const 但不接受字面量
问题描述
在编写模板时,class T
可以用const
类型代替。
考虑:
template<class T> T& min(T& a, T& b) {
return a < b ? a : b;
}
这将在以下情况下起作用:
int a = 1, b = 5;
const int c = 1, d = 5;
min(a, b); // T is int
min(c, d); // T is const int
但是当使用文字调用时会抛出编译错误(像这样):
min(1, 5); // T is const int literal
从“int”类型的右值初始化“int&”类型的非常量引用无效</p>
为什么?不是 int 文字 aconst int
吗?以及如何修改模板以允许使用文字?
(与 gcc 6.3 和 MSVC 2015 一致)
解决方案
int
文字有类型int
,没有const int
。T
因此推断为int
,并且int&
不能绑定到 prvalue。
编写这样一个函数的正确方法是完善转发参数,或者使用const T&
,两者都可以绑定到任何东西。
template<typename T, typename U>
auto min(T&& a, U&& b) -> decltype(a < b ? std::forward<T>(a) : std::forward<U>(b))
{
return a < b ? std::forward<T>(a) : std::forward<U>(b);
}
// Or...
template<typename T>
const T& min(const T& a, const T& b)
{
return a < b ? a : b;
}
在完美转发参数的情况下,需要两个模板参数才能int a{}; min(a, 42);
编译,因为它们推导的类型不同。
推荐阅读
- ios - iOS 推送通知服务扩展不一致的工作
- sql - SQL联合但垂直
- java - 带有 Jackson 的自定义 JSON 字段作为响应
- sql - 列表和标签 - 如果辅助表没有值,则隐藏主表值
- html - CSS:背景不透明度显示在文本上
- mysql - mysql单列值到多列按另一列值分组
- apache - Nextcloud 在 apache 和 nginx 上作为反向代理 + SSL
- php - 如何使用 php 在日历中突出显示事件日期并显示事件标题?
- java - 如何在 Java Swing 应用程序中播放 MP4 视频
- openfoam - sonicFoam forwardStep 现实边界条件导致错误::printStack(Foam::Ostream&)