Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a C++ template to pass a value in the best way?

Tags:

c++

templates

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.

like image 669
Zhen Avatar asked Oct 05 '12 18:10

Zhen


People also ask

What is a template argument?

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.

What is the difference between class template and function template?

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.

What does template C++?

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.

What is non type template parameters?

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> ).


1 Answers

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);
like image 187
Rost Avatar answered Oct 04 '22 12:10

Rost