c++ - 模板化模板参数 U不识别 const 限定符
问题描述
我正在研究以下代码(没有真正的应用程序,只是出于好奇):
#include <memory>
template <typename T>
struct MyClass{};
template <template <class> class U, class T>
void foo(std::shared_ptr<U<T>> t){ }
template <class U>
void bar(std::shared_ptr<U> t){ }
int main()
{
std::shared_ptr<const MyClass<int>> ptr_to_const;
std::shared_ptr<MyClass<int>> ptr;
foo(ptr_to_const); // error
foo(ptr); // OK
bar(ptr_to_const); // OK
bar(ptr); // OK
}
但是,编译器失败了
<source>: In function 'int main()':
<source>:17:9: error: could not convert 'ptr_to_const' from 'shared_ptr<MyClass<[...]>>' to 'shared_ptr<MyClass<[...]>>'
17 | foo(ptr_to_const); // error
| ^~~~~~~~~~~~
| |
| shared_ptr<MyClass<[...]>>
现场演示在这里。似乎在使用模板模板参数时忽略了 const 限定符,如foo
. 有人可以解释一下为什么这不会编译吗?正如预期的那样,调用bar
不会导致任何问题。
解决方案
是模板推演失败。
没有U
和的组合T
可以匹配std::shared_ptr<U<T>>
from std::shared_ptr<const MyClass<int>>
。const MyClass
不是模板。
你可以超载foo
template <template <class> class U, class T>
void foo(std::shared_ptr<const U<T>> t){ }
template <template <class> class U, class T>
void foo(std::shared_ptr<volatile U<T>> t){ }
template <template <class> class U, class T>
void foo(std::shared_ptr<const volatile U<T>> t){ }
推荐阅读
- python - 从文本文件 Python 中查找最新的列
- python - Python - 当 Pygame 窗口在使用 Tkinter 后聚焦时,在已删除的表上调用 Tcl_FindHashEntry
- javascript - 如何使用 SharePoint Plus api 在 SharePoint Designer 2013 中获取 SharePoint“审批状态”列数据
- python - 对剩余组的非零值进行切片后的 Pandas groupby 平均值
- javascript - 当我用另一个类似的函数替换函数调用时,nodejs aync 函数需要更多时间
- acumatica - 在项目页面中上传图像时调整图像大小
- python - 估计部分观察到的动态系统中的参数?
- python - 检查输入时出错:预期 lstm_input 有 3 个维度,但得到了形状为 (5, 10) 的数组
- powerbi - 如何在 Power BI 中合并包含相同 ID 的行并删除重复行的空值
- three.js - 希望通过使用另一个对象的轴心点来旋转一个对象