简体   繁体   English

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

[英]Question about overloaded operator T() in C++ template class

I have this little piece of code:我有一小段代码:

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;
}

It doesn't compile unless the line operator T() const { return toto; }除非 line operator T() const { return toto; }否则它不会编译。 operator T() const { return toto; } is un-commented. operator T() const { return toto; }未注释。 This magically works, but I am not sure why (if I un-comment the line).这很神奇,但我不确定为什么(如果我取消注释该行)。

I do understand that if the line is commented, the type of a when passed to function() is incompatible with the expected type int* .我确实明白,如果该行被注释,则传递给function()时的a类型与预期的类型int*不兼容。 So, of course, the compiler complains... no problem.所以,当然,编译器抱怨......没问题。

I also understand that the operator returns the actual type of the object, therefore in this particular case the compiler is happy.我也知道该运算符返回 object 的实际类型,因此在这种特殊情况下编译器很高兴。

I don't understand why the operator is called in this particular case.我不明白为什么在这种特殊情况下调用运算符。

Is doing function(a) the same thing as doing function(a()) , only the () are implicit?function(a)和做function(a())一样吗,只有()是隐含的?

operator T() const { return toto; } operator T() const { return toto; } is a user defined conversion operator , it is not operator() . operator T() const { return toto; }用户定义的转换运算符,它不是operator() It's used to define that your class is convertible to a different type.它用于定义您的 class 可转换为不同的类型。

operator() would look like this instead: operator()看起来像这样:

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

In your case, you are using int* as T .在您的情况下,您使用int*作为T If you substitute it yourself in the operator, you will see that it becomes operator int*() const { return toto; }如果你自己在运算符中替换它,你会看到它变成了operator int*() const { return toto; } operator int*() const { return toto; } which means "my class can be converted to an int* and the result of that conversion is evaluated as return toto; ". operator int*() const { return toto; }这意味着“我的 class 可以转换为int*并且该转换的结果被评估为return toto; ”。

The function function() only accepts an int* as its argument. function function()仅接受int*作为其参数。 When you provide a Test instance, the call is only legal if there is a way to convert from Test to int* , which is why the operator T is required for the code to compile.当您提供一个Test实例时,只有当有一种方法可以将Test转换为int*时,该调用才是合法的,这就是编译代码需要operator T的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM