使用 libtorch 时,以下代码片段会导致错误:
#include <iostream>
#include <torch/torch.h>
using namespace torch;
int main() {
std::cout << zeros({}) << std::endl;
}
编译器抱怨:
% g++ -lc10 -ltorch -ltorch_cpu test.cpp -o test.x
test.cpp: In function ‘int main()’:
test.cpp:5:23: error: call of overloaded ‘zeros(<brace-enclosed initializer list>)’ is ambiguous
5 | std::cout << zeros({}) << std::endl;
| ~~~~~^~~~
In file included from /opt/links/include/ATen/Functions.h:1334,
from /opt/links/include/ATen/ExpandUtils.h:4,
from /opt/links/include/torch/csrc/autograd/input_metadata.h:3,
from /opt/links/include/torch/csrc/autograd/function.h:7,
from /opt/links/include/torch/csrc/autograd/custom_function.h:7,
from /opt/links/include/torch/csrc/api/include/torch/autograd.h:5,
from /opt/links/include/torch/csrc/api/include/torch/all.h:7,
from /opt/links/include/torch/csrc/api/include/torch/torch.h:3,
from test.cpp:2:
/opt/links/include/ATen/ops/zeros.h:35:19: note: candidate: ‘at::Tensor at::zeros(IntArrayRef, c10::TensorOptions)’
35 | inline at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options={}) {
| ^~~~~
In file included from /opt/links/include/torch/csrc/api/include/torch/types.h:7,
from /opt/links/include/torch/csrc/api/include/torch/data/dataloader_options.h:4,
from /opt/links/include/torch/csrc/api/include/torch/data/dataloader/base.h:3,
from /opt/links/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:4,
from /opt/links/include/torch/csrc/api/include/torch/data/dataloader.h:3,
from /opt/links/include/torch/csrc/api/include/torch/data.h:3,
from /opt/links/include/torch/csrc/api/include/torch/all.h:9:
/opt/links/include/torch/csrc/autograd/generated/variable_factories.h:565:19: note: candidate: ‘at::Tensor torch::zeros(at::IntArrayRef, c10::TensorOptions)’
565 | inline at::Tensor zeros(at::IntArrayRef size, at::TensorOptions options = {}) {
| ^~~~~
为什么他at::zeros
被列为候选人而我不是using namespace at
?
关于此类错误还有许多其他问题,我认为它们无法回答我的问题:
- 错误:尝试定义一个带有和不带有可选/默认参数的函数
不相关,因为:两个变体都定义在同一个命名空间中
问题:1 2 - 错误:#include 了头文件的 C 版本,而不是 C++ 版本
不相关,因为:据我所知,libtorch 没有 C 接口
问题:1 2 - 错误:在两个不同的命名空间中声明了相同的函数(非常接近!)
不相关,因为:两个命名空间都已纳入范围,一个接using
一个地现在位于该命名空间中,而在我看来,其中一个声明的候选者似乎不应该在我的范围内
问题:1 2 - 错误:所有可用的重载都没有正确的类型
不相关,因为:两个候选都具有相同的类型,并且与调用相匹配;例如,更改zeros
为torch::zeros
可使文件编译
问题:1 2 3
还有更多;我承认我此时感到很沮丧并放弃浏览它们。
因为 pytorch 标头包含
命名空间内的指令
torch
。请参阅此处。因为您使用了
using namespace torch;
它,所以它还可以使所有内容at
在全局范围内可用。链接行上方的注释表明他们没有考虑用户使用
using namespace torch;
order 进行非限定调用。他们似乎希望用户进行限定调用。正如注释所述,限定查找的行为有所不同。