How to cast/change Tensor dtype in C++?

Hi everyone,

Does anyone know how one can cast a Tensor to a different torch::dtype() in C++?

In Python this appears to be as simple as .float() (for torch::dtype(torch::kFloat32)) and .double() (for torch::dtype(torch::kFloat64)).

Thank you.

1 Like

You can use the to method:

#include <torch/torch.h>
#include <iostream>

int main() {
    torch::Tensor tensor = torch::rand({2, 3});
    auto x = tensor.to(torch::kInt);
  std::cout << tensor << std::endl;
  std::cout << x << std::endl;
}
1 Like

Thank you very much! :smile:

1 Like