Even better solution in the manual - https://pytorch.org/cppdocs/api/classtorch_1_1nn_1_1_module.html#exhale-class-classtorch-1-1nn-1-1-module 110
template < typename ModuleType, typename = torch::detail::disable_if_module_holder_t 1>
ModuleType * as ()
Attempts to cast this Module to the given ModuleType .
This method is useful when calling apply() .
void initialize_weights(nn::Module& module) { torch::NoGradGuard no_grad; if (auto* linear = module.asnn::Linear()) { linear->weight.normal_(0.0, 0.02); } } MyModule module; module.apply(initialize_weights);