繁体   English   中英

使用 + 后跟:: (C++ 代码中的范围解析运算符

[英]use of + followed by :: (scope resolution operator in C++ code

我有以下 C++ 代码片段:

inline std::vector<std::unique_ptr<xir::Tensor>> cloneTensorBuffer(
    const std::vector<const xir::Tensor*>& tensors)
{
    auto ret = std::vector<std::unique_ptr<xir::Tensor>>{};
    auto type = +::DataType::XINT;
    ret.reserve(tensors.size());
    for (const auto& tensor : tensors) {
        ret.push_back(std::unique_ptr<xir::Tensor>(xir::Tensor::create(
            tensor->get_name(), tensor->get_shape(), xir::DataType{type, 8u})));
    }
    return ret;
}

我不清楚声明:

auto type = +::DataType::XINT;

+后跟:: :(范围解析运算符)是什么意思?

该组合没有特殊含义。 +是常规前缀运算符。 在这种特殊情况下,它可能是多余的,或者对int执行强制。 但是,实际含义可能会有所不同,具体取决于::DataType::XINT类型的重载方式。

::是常规的 scope 分辨率运算符。 当在子表达式的开头使用时(即没有左操作数),它会导致在顶部 scope执行查找,即它忽略嵌套 scope 中DataType的任何阴影重新定义:

int x = 1;

void f() {
    int x = 2;
    std::cout << "inner = " << x << "\n";   // inner = 2
    std::cout << "outer = " << ::x << "\n"; // outer = 1
}

没有+:: 它是一元+运算符和::运算符。

::foo指的是全局命名空间中的foo 当当前命名空间中有另一个DataTye::XINT时,可能需要它。

一元+有时用于触发隐式转换。 您需要检查::DataType::XINT是什么类型以及它有哪些可用的转换。

由于我不知道::DataType::XINT是什么,这里是一个带有 lambda 表达式的示例:

template <typename T>
void foo();

int main() {
    auto x = [](){};
    foo(x);
    foo(+x);
}

错误消息(缩短)是:

<source>:6:8: error: no matching function for call to 'foo(main()::<lambda()>&)'
    6 |     foo(x);
<source>:7:8: error: no matching function for call to 'foo(void (*)())'
    7 |     foo(+x);
      |     ~~~^~~~

You can see that foo(x) tries to call foo with the lambda, while in foo(+x) the lambda was implicitly converted to a function pointer (because of ClosureType::operator ret(*)(params)() and +可用于 function 指针,但不适用于 lambdas 类型)。

暂无
暂无

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

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