The RAII torch::AutoGradMode enable_grad(true/false); should work as described in the docs 4.
auto x = torch::tensor({1.}, torch::requires_grad());
{
  torch::AutoGradMode enable_grad(true);
  auto y = x * 2;
  std::cout << y.requires_grad() << std::endl; // prints `true`
}
{
  torch::AutoGradMode enable_grad(false);
  auto y = x * 2;
  std::cout << y.requires_grad() << std::endl; // prints `false`
}