3

In GCC 4.9.2 the following code fails to compile:

#include <chrono>
#include <string>

using namespace std::literals::string_literals;
using namespace std::literals::chrono_literals;

template<typename T>
struct S
{
    S()
    {
        "hello"s;
    }
};

int main()
{
    S<int> s;
}

giving errors starting with:

error: no matching function for call to 'operator""s()'

There are no errors if I comment out the chrono_literals line, and no errors for a non-template class.


I presume this is a gcc 4.9 bug, since the same code works in GCC 5, and clang. My question is: is there a workaround I can put in place so that I can use both std::string literals and chrono literals in a template with this compiler version?

For example, something I could edit in one of the standard headers, or something I could do globally in my code?

Note: this compiler version does not have an implied using namespace std::literals::chrono_literals as the C++ Standard appears to mandate; that was added in GCC 5 also.

M.M
  • 138,810
  • 21
  • 208
  • 365

1 Answers1

3

If you don't need to use both in the same scope, then just have the using where needed.

Otherwise I'd reimplement my own string literals based on the libstdc++ header and call them something different than s (which you'd get warnings about anyway)... say _s. Of course, you can also implement your own chrono literals, but those seem to be a little more involved.

#include <string>   
#include <chrono>


inline std::basic_string<char>
operator""_s(const char* __str, size_t __len)
{ return std::basic_string<char>{__str, __len}; }


template<typename T>
struct S
{
    S()
    {
        {
            using namespace std::literals::chrono_literals;
            10s;
            "hello"_s;
        }
        {
            using namespace std::literals::string_literals;
            "hello"s;
        }
    }
};

int main()
{
    S<int> s;
}

code on godbolt

Dan Mašek
  • 17,852
  • 6
  • 57
  • 85