I seem to remember I way to select value-pass or reference-pass of a parameter using the size of the type.
Something like:
void fun( check<A> a ){
...
}
Generates or:
void fun( A a ){
...
}
or
void fun( A & a ){
...
}
Depending of the size of type A and the architecture where you compile the applicacion.
A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.
With the introduction of C++20, it's now possible to provide a literal class type (i.e. constexpr class) instance as a template parameter. As a refresher, a non-type template parameter is a template parameter that does not name a type, but rather, a constant value (e.g. template<int value> ).
In C++11 you can use std::conditional
:
#include <type_traits>
class A { ... };
typedef std::conditional<
std::is_trivially_copyable<A>::value && sizeof(A) <= sizeof(int),
A, const A&>::type AParam;
// Direct usage
void f(AParam param);
// Wrap into template class
template <typename T> struct check:
std::conditional<std::is_arithmetic<T>::value, T, const T&> {};
void f(check<A>::type param);
For C++03 compilers you could use Boost implementation - Boost.TypeTraits library.
As @sehe mentioned there is also Boost.CallTraits library that correctly implements required functionality:
#include <boost/call_traits.hpp>
class A { ... };
void f(boost::call_traits<A>::param_type param);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With