c++ - 自动模板推导中的 const 正确性
问题描述
在下面的示例中,我希望该行将a.foo(j);
const 限定符传递给模板化方法。
#include <iostream>
#include <type_traits>
struct A
{
template<typename T>
void foo(T i) const
{
std::cout << "Is const type: " << std::is_const<T>::value << "\n";
}
};
int main() {
A a;
int i = 0;
const int j = 0;
a.foo(i);
a.foo(j);
a.foo<decltype(i)>(i);
a.foo<decltype(j)>(j);
a.foo<int>(i);
a.foo<const int>(j);
return 0;
}
然而,我从 gcc 和 clang (c++17) 得到的输出如下。
Is const type: 0
Is const type: 0
Is const type: 0
Is const type: 1
Is const type: 0
Is const type: 1
第二行是假而不是真。那么为什么自动模板推导会丢弃 cv 限定词呢?发生这种情况有什么具体原因吗?
PS。上面的例子可以在这里找到
解决方案
对类型的扣除T
总是会衰减的。的衰减类型int const
是简单的int
。a 的衰减类型int[3]
是int*
。
问题是,这段代码是正确的。
是的,在里面foo
你永远无法改变j
. 在里面foo
你有一个副本,由它foo
来决定它是否希望它自己的参数在函数体内保持不变。
但是,还有其他形式的推导必须保持const
可与参数一起调用。这不是您的代码的解决方案,而只是一个示例:
template<typename T>
void frob(T& i)
{
std::cout << "Will it be const? " << std::is_const<T>::value << "\n";
}
auto main() -> int {
int const myInt = 9;
frob(myInt);
}
要被调用,参数必须是int const&
这样才能推导出来。
推荐阅读
- amazon-web-services - IAM 角色的 AWS CloudFormation 下拉菜单
- git - 冲突的 GIT 分支同时合并的结果
- python - Visual Studio Python 启动 pip.exe,调试 setup.py
- swift - swift @objc 和选择器:从选择器返回类型的编译器错误
- webpack - 浏览器如何请求哈希文件名
- jquery - Jquery nice select plugin is not working properly
- java - 从 Jfilechooser 检索文件名到 JList
- reactjs - 使用 useCallback 记住一个闭包和渲染回调
- javascript - KrakenD 的跨域读取阻塞 (CORB) 问题 - 来自 POST 的“应用程序/json”响应被 Chrome 拒绝
- python - 我想弄清楚为什么我的字符串不会连接