Note: I am using gcc, but tested on godbolt.org and it also works on msvc, but not on clang
I accidentally discovered that the following simple function compiles while being in a templated class, but not as a free function. Could someone explain why?
Compiles OK:
template <typename T = void>
class A
{
public:
static constexpr std::string f()
{
return std::string();
}
}
Doesn't compile:
constexpr std::string f()
{
return std::string();
}
Throws error:
error: invalid return type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} of ‘constexpr’ function ...
...
/usr/include/c++/9/bits/basic_string.h:77:11: note: ‘std::__cxx11::basic_string<char>’ is not literal because:
77 | class basic_string
| ^~~~~~~~~~~~
/usr/include/c++/9/bits/basic_string.h:77:11: note: ‘std::__cxx11::basic_string<char>’ has a non-trivial destructor