0

I'm trying to load text from a file into a const char* instance. I came across this answer and adapted it as:

std::ifstream vertex_shader_stream("shaders/demo1_vert.glsl");
std::string vertex_shader_string(
  (std::istreambuf_iterator<char>(vertex_shader_stream)),
  std::istreambuf_iterator<char>());
const char *vertex_shader_bytes = vertex_shader_string.c_str();

What I'm having trouble understanding is why the first argument to std::string is wrapped in parens () as (std::istreambuf_iterator<char>(vertex_shader_stream)). I thought this might have been some redundant typing, but it appears to fail without them when calling c_str

error: request for member ‘c_str’ in ‘vertex_shader_string’, which is of non-class type ‘std::string(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())’ {aka ‘std::__cxx11::basic_string<char>(std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> > (*)())’}
[build]    61 |   const char *vertex_shader_text = vertex_shader_string.c_str();
[build]       |                                                         ^~~~~

I'm not groking the error here, can someone explain this to me in detail what's going on? I'm sure this is probably a duplicate, so feel free to close vote if that's the case, I just don't know the right terms to search for!

Thanks!

flakes
  • 21,558
  • 8
  • 41
  • 88
  • 3
    [Most vexing parse](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse) ? – Jason Apr 03 '23 at 03:09
  • 2
    See dupe [How can I avoid most vexing parse with direct value initialization?](https://stackoverflow.com/questions/51707710/how-can-i-avoid-most-vexing-parse-with-direct-value-initialization) – Jason Apr 03 '23 at 03:10
  • @Jason Thanks so much. I don't think I would have found that on my own quickly. These cpp concepts have such out to lunch names sometimes. – flakes Apr 03 '23 at 03:11
  • @Jason So if I'm reading this correctly, the compiler thought I was making a function called `vertex_shader_string` where the first argument is a `std::istreambuf_iterator` ? – flakes Apr 03 '23 at 03:17
  • 1
    Yes, exactly. See the warning [here](https://godbolt.org/z/sno3donWa). This is why it is recommended to [always enable all warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings). – Jason Apr 03 '23 at 03:20
  • 1
    @Jason Yep, would have thought warnings would be the default. Getting all my ducks in a row for starting cpp dev is going to be an interesting ride. Thanks again! – flakes Apr 03 '23 at 03:28

0 Answers0