注意:我使用的是 gcc,但在 godbolt.org 上进行了测试,它也适用于 msvc,但不适用于 clang
我偶然发现以下简单函数在模板类中编译,但不是作为自由函数。有人可以解释为什么吗?
编译正常:
template <typename T = void>
class A
{
public:
static constexpr std::string f()
{
return std::string();
}
}
不编译:
constexpr std::string f()
{
return std::string();
}
抛出错误:
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