# Libtorch Polymorphism

**URL:** <https://discuss.pytorch.org/t/libtorch-polymorphism/134063>\
**Category:** C++\
**Created:** [October 12, 2021, 7:41pm UTC](https://discuss.pytorch.org/t/libtorch-polymorphism/134063 "2021-10-12T19:41:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jackshi](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jackshi/32/34660_2.png) [@jackshi](https://discuss.pytorch.org/u/jackshi)\
**Post date:** [October 12, 2021, 7:41pm UTC](https://discuss.pytorch.org/t/libtorch-polymorphism/134063/1 "2021-10-12T19:41:14Z")

</div>

Libtorch uses CRTP to make cloneable modules. For example, `torch::nn::Softmax` is a `ModuleHolder<SoftmaxImpl>` and `SoftmaxImpl` is a `torch::nn::Cloneable<SoftmaxImpl>`.

Say I want a `std::vector<Module>` or a function that returns a activation function that’s also a `Module`. I have to cast various modules such as `torch::nn::Softmax` to `torch::nn:Module`. This means I loose `Cloneable` which I’m not sure is a problem. If I return a reference by simply dereferencing `ModuleHolder`, since it’s a shared pointer, I’m not sure if the underlying module is guaranteed to survive.

Any advice on how to get around `Cloneable` and `ModuleHolder` to work with generic `torch::nn::Module` (so I can have a function that returns it or a `std::vector` of it) is much appreciated!

---

<div class="post-metadata">

**Author:** ![jackshi](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jackshi/32/34660_2.png) [@jackshi](https://discuss.pytorch.org/u/jackshi)\
**Post date:** [October 12, 2021, 9:39pm UTC](https://discuss.pytorch.org/t/libtorch-polymorphism/134063/2 "2021-10-12T21:39:42Z")

</div>

Solved: use AnyModule.
