Answer the question
In order to leave comments, you need to log in
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;
Answer the question
In order to leave comments, you need to log in
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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question