std::string 的专用静态模板函数未被调用

Specialized static template function to std::string is not called

我的 class 中有一个静态模板函数,就像这样:

file.hpp:

class File
{
public:
    template<typename Type>
    static Type read(const std::string & fullPath, const std::ios_base::openmode mode = std::ios_base::in);
};

template<typename Type>
Type File::read(const std::string & fullPath, std::ios_base::openmode mode)
{
  std::stringstream ss;
  ss << readImpl(fullPath, mode);

  Type value = Type();
  ss >> value;

  return value;
}

file.cpp:

template<>
std::string File::read(const std::string & fullPath, std::ios_base::openmode mode)
{
  return readImpl(fullPath, mode);
}

readImpl 只是 return 一个字符串。

所以,我的问题是为什么当我 运行 类似这样的事情时,我对 std::string 的读取方法的专门化没有被调用:

 const std::string content = File::read<std::string>(path);

谢谢

您可以做以下事情:

file.cpp

template<>
std::string File::read(const std::string & fullPath, std::ios_base::openmode mode)
{
  return readImpl(fullPath, mode);
}

template std::string File::read(const std::string&, std::ios_base::openmode);

但实际上在头文件中写专业化会更好