首页 > 解决方案 > 为什么这个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>();
}

标签: c++c++11templatesc++17

解决方案


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>();
}

推荐阅读