将代码移出 main 函数,出现错误 "implicit instantiation of undefined template"

Moving code outside of main function, getting error "implicit instantiation of undefined template"

我正在考虑实现 slurp,一个读取文件和 returns 字符串的函数:

当此代码在 main() 函数中时,它工作正常:

int main(){
  std::ifstream ifs("stuff.txt");
  std::string content((std::istreambuf_iterator<char>(ifs)),
                      (std::istreambuf_iterator<char>()));
  std::cout << content;
  return 0;
}

但是,当我将文件移出到另一个文件中的函数时:

std::string slurp(std::string filename){
  std::ifstream ifs(filename);
  std::string content((std::istreambuf_iterator<char>(ifs)),
                      (std::istreambuf_iterator<char>()));
  return content;
}

我在编译时遇到这样的错误:

[ 33%] Building CXX object CMakeFiles/image_calibration.dir/source/cpp/kanya.cpp.o
/Users/chris/Development/chit/image-bench/source/cpp/kanya.cpp:15:19: error: implicit instantiation of undefined template 'std::__1::basic_ifstream<char,
std::__1::char_traits<char> >'
std::ifstream ifs(filename);
          ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/iosfwd:131:32: note: template is declared here
class _LIBCPP_TEMPLATE_VIS basic_ifstream;

发生了什么事?

可能你只是错过了:

#include <fstream>