0

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?

3
  • 6
    Isn't N a function in the second case? Commented Apr 14, 2020 at 20:30
  • You need to call that function. Commented Apr 14, 2020 at 20:31
  • 3
    C::N is a function pointer, which gets converted to a bool for output. See this question. Commented Apr 14, 2020 at 20:35

2 Answers 2

1

The problem here is coming from the differences between your two 'N' declarations. In the first case static const inline string N {"abc"}; is a string variable. In the second case static std::string& N() is a function. This is why when you use C::N the first time it works, it is the same as using "abc" in its place because it is just a string variable. This is also why it does not work as expected in the second case: C::N is a function not a variable in the typical sense. So to run the function you must call it by using C::N() which does output a string.

Edit: See @1201ProgramAlarm's comment on your question for the reason you get a 1 when the function isn't called.

Sign up to request clarification or add additional context in comments.

Comments

0

Seems that it can be easily solved by adding a () after N for the 2nd case:

#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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.