c++ - 为什么这个c++模板场景无法编译:
问题描述
struct stream_type1 {
template<typename T>
const T& read() const;
};
struct stream_type2 {
template<typename T>
const T& read() const;
};
template<typename S, typename T>
const T& stream_read(const S& stream)
{
return stream.read<T>();
}
// example:
stream_type1 stream1;
stream_type1 stream2;
int value1 = stream_read<int>(stream1);
int value2 = stream_read<int>(stream2);
错误:C2665: 'stream_read':2 个重载都不能转换所有参数类型
所以,我必须专门化模板女巫使它变得多余
template<typename T>
const T& stream_read(const stream_type1 & stream)
{
return stream.read<T>();
}
template<typename T>
const T& stream_read(const stream_type2 & stream)
{
return stream.read<T>();
}
解决方案
You have your template parameters the wrong way round to deduce the stream type. At the moment you have instantiated it as
template<typename T>
const T& stream_read(const int& stream)
{
return stream.read<T>();
}
You can swap T
and S
template<typename T, typename S>
const T& stream_read(const S& stream)
{
return stream.read<T>();
}
推荐阅读
- flutter - 我想在将其作为参数传递之前填写列表
- javascript - Chrome扩展机宽存储
- r - 如何用 r 中数据框的每一列中存在的值填补空白?
- r - 如何从数据帧创建频率矩阵
- java - 我怎样才能正确地从表单中获取数据
- sorting - 关于在单个代码中对字典进行排序,就像我想要在单个字典中同时按键和值排序的字典
- react-native - 将异步存储与 React Navigation 结合使用(React Native)
- php - 我正在寻找 php-info 文件的替代品,因为我所在的服务器不允许它运行,我可以使用任何替代代码吗?
- for-loop - 如何减少每个像素的迭代?
- javascript - “for await of”的控制流程是什么?