T
T
tugo2015-10-21 15:19:49
Programming
tugo, 2015-10-21 15:19:49

C++ templates - is it possible to generate different code depending on the size of the passed type?

Why is it necessary.
I want to write my own C ++ wrapper over the means of transferring data between RTOS threads.
There are several means of data exchange:
1. Queue https://developer.mbed.org/handbook/RTOS#queue
Allows you to transfer data of 4 bytes. Inside the Queue class, the data is cast to the uint32_t type.
2. Combination of Queue and MemoryPool. https://developer.mbed.org/handbook/RTOS#memorypool
In the queue we pass a pointer to the data, in the MemoryPool the data itself.
The syntax for putting and retrieving data is different.
I want to create a generic GenericQueue class that can hold data of any size (data type is determined at compile time). If 4 bytes of data fit, a simpler code with Queue is generated. If the data is larger, the code with Queue + MemoryPool is generated.

GenericQueue<float, 10> floatQueue;
GenericQueue<double, 5> dobleQueue;
GenericQueue<SomeStruct, 5> structQueue;

How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2015-10-21
@MiiNiPaa

Something like this:

#include <iostream>
#include <type_traits>
#include <typeinfo>

template <typename T>
class GenericQueueBase
{
  //Общий интерфейс очереди (для рантайм полиморфизма)
};

template <typename T>
class Queue_pass : public GenericQueueBase<T>
{
    static_assert(sizeof(T) <= 4, "types up to 4 bytes are allowed");
    //Реализация очереди
};

template <typename T>
class Pool_pass : public GenericQueueBase<T>
{
    //Реализация пула
};


template<typename T>
using GenericQueue = typename std::conditional<sizeof(T) <= 4, Queue_pass<T>, Pool_pass<T>>::type;

int main()
{
  std::cout << typeid(GenericQueue<int>).name() << '\n' << typeid(GenericQueue<double>).name();
}

M
maaGames, 2015-10-21
@maaGames

You should not be attached to the size, you should be attached to the type.
But it is also possible to the size if the size is converted to a type:
template< int SZ >
struct SizeType
{
enum { TypeSize = SZ };
};
SizeType and SizeType are different types.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question