c++c++17inlineheader-only

C++ how to call header-only library


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?


Solution

  • 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.