Member-only story
Passing Any Type in C++ Like in Python to Simplify Our Code
Understanding how Any Type like std::any can help us simplify our code and how it works under the hood so that we can determine whether it satisfies our needs when developing our applications
We first discuss why we need to use Any Type, with examples, followed by how it is implemented using the Type Erasure technique, and finally how it allocates memory to see whether it fits our needs for writing our applications in C++.
Passing Any Type — Why we need it
Dynamically Typed Language
In a dynamically typed programming language like Python, we can pass any type to a function and does check at runtime whether it has the attribute that the function needs or not. For example, the function has a parameter called input.
If we pass a wrong parameter type, for instance, an int, function(3)
, an exception AttributeError will be raised.
AttributeError: 'int' object has no attribute 'x'
When we pass a type that has an ‘x’ attribute, our function is executed successfully. The same goes to methods, if the method with the same name exists, it will be executed, otherwise an exception is raised.
Statically Typed Language
In a statically typed programming language like C++, we strictly need a type for our parameter. Unlike Python, type checking is performed at compile-time, that’s why we need to know the type.
If we pass a wrong parameter type, for instance, an int, function(3)
, we’ll get the following compile…