关于C++模板类中重载运算符T()的问题

use*_*490 0 c++ operator-overloading

我有这么一小段代码:

template<typename T>
class Test
{
public:
    //operator T() const { return toto; }
    T toto{ nullptr };
};

void function(int* a) {}

int main(int argc, char** argv)
{
    Test<int*> a;
    function(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

除非该行未被注释,否则它不会编译operator T() const { return toto; }。这神奇地起作用,但我不确定为什么(如果我取消注释该行)。

a我确实理解,如果该行被注释,则传递给的类型function()与预期的类型不兼容int*。所以,编译器当然会抱怨……没问题。

我还了解运算符返回对象的实际类型,因此在这种特殊情况下编译器很高兴。

我不明白为什么在这种特殊情况下调用操作员。

做与function(a)做同样的事情function(a()),只是()隐式的吗?

Fra*_*eux 5

operator T() const { return toto; }用户定义的转换运算符,但它不是operator()。它用于定义您的类可以转换为不同的类型。

operator()看起来像这样:

void operator()() const { ... }

就您而言,您正在使用int*as T。如果您自己在运算符中替换它,您将看到它变成operator int*() const { return toto; }这意味着“我的类可以转换为 anint*并且该转换的结果被评估为return toto;”。

该函数function()仅接受 anint*作为其参数。当您提供Test实例时,仅当有一种方法可以从 转换Test为 时int*,调用才是合法的,这就是operator T代码编译时需要 的原因。