I learnt C++17 way of dealing with header-only library, by adding inline keyword:
#include <iostream> #include <string> using namespace std; struct C { static const inline string N {"abc"}; }; int main() { cout << C::N << endl; return 0; } Running above piece of code returns abc as expected.
However, if I tried to use the pre-C++17 style as below:
#include <iostream> #include <string> using namespace std; struct C { static std::string& N() { static std::string s {"abc"}; return s; } }; int main() { cout << C::N << endl; return 0; } I got result of 1 rather than the expected abc. I'm wondering why and how to fix it?
Na function in the second case?C::Nis a function pointer, which gets converted to aboolfor output. See this question.