我有一个包装器类,其行为应类似于指针。我已经过载operator T*和operator bool。布尔进行了一些额外的验证。我尝试在if中使用该对象,但我注意到该operator T*对象称为和bool。有人可以解释我为什么吗?是在标准中以某种方式指定的吗?我在MSVC,clang和gcc中测试了以下示例代码,它们都调用operator T*。另外,根据我在此页面上阅读的内容(https://en.cppreference.com/w/cpp/language/implicit_conversion),if应该尝试转换为bool。
#include <stdio.h>
class MyClass
{
public:
MyClass(int i)
: m(i)
{}
operator bool() const
{
printf("operator bool()\n");
return m;
}
operator int* ()
{
printf("operator int* ()\n");
return &m;
}
private:
int m;
};
int main()
{
MyClass a(5);
MyClass b(0);
if (a)
printf("a is true\n");
else
printf("a is false\n");
if (b)
printf("b is true\n");
else
printf("b is false\n");
return 0; …Run Code Online (Sandbox Code Playgroud) c++ class operator-overloading conversion-operator implicit-conversion
注意:我使用的是 gcc,但在 godbolt.org 上进行了测试,它也适用于 msvc,但不适用于 clang
\n我意外地发现以下简单函数在模板类中进行编译,但不能作为自由函数进行编译。有人可以解释为什么吗?
\n编译正常:
\n template <typename T = void>\n class A\n {\n public:\n static constexpr std::string f()\n {\n return std::string();\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n不编译:
\n constexpr std::string f()\n {\n return std::string();\n }\nRun Code Online (Sandbox Code Playgroud)\n抛出错误:
\nerror: invalid return type \xe2\x80\x98std::string\xe2\x80\x99 {aka \xe2\x80\x98std::__cxx11::basic_string<char>\xe2\x80\x99} of \xe2\x80\x98constexpr\xe2\x80\x99 function ...\n...\n/usr/include/c++/9/bits/basic_string.h:77:11: note: \xe2\x80\x98std::__cxx11::basic_string<char>\xe2\x80\x99 is not literal because:\n 77 | class basic_string\n | ^~~~~~~~~~~~\n/usr/include/c++/9/bits/basic_string.h:77:11: note: \xe2\x80\x98std::__cxx11::basic_string<char>\xe2\x80\x99 has a non-trivial destructor\nRun Code Online (Sandbox Code Playgroud)\n