I want to use a templated structure in order to mimic an array of doubles in 4 dimensions, the maximum size for each dimension is know in compilation time. Therefore, I think that using templates structure will give a chance to gain performance. You can find my attempt for the implementation bellow.
The code compiles unless that I attempt to instantiate one structure. I don't understand what is the problem with the code bellow, suggestions will be very appreciated.
Even more, I want to do two improvements if possible: 1) I want to be capable of use data of type float and of type double 2) Will be fancy to have some kind of overloaded operator that enables to assign values to the records of data in a similar way as T(N,L,M,J)=val in place of having to use T.assign(N,L, M,J,value). Again, suggestions will be very appreciated.
My aim is to fill the data in T_4D as fast as possible.
#include <iostream>
#include <cstring> // for memset
using namespace std;
template <size_t dim_N=3,size_t dim_L=3,size_t dim_M=3,size_t dim_J=10,double *data=NULL>
struct T_4D {
enum {SIZE = dim_N*dim_L*dim_M*dim_J };
enum {LEN1 = dim_N };
enum {LEN2 = dim_L };
enum {LEN3 = dim_M };
enum {LEN4 = dim_J };
static void create()
{
data=(double *)malloc(SIZE*sizeof(double));
memset(data, 0.0, SIZE*sizeof(*data));
}
static size_t multi_index(const size_t N) {
return N;
}
static size_t multi_index(const size_t N,const size_t L) {
return L*dim_N + N;
}
static size_t multi_index(const size_t N,const size_t L, const size_t M) {
return (M*dim_L + L)*dim_N + N;
}
static size_t multi_index(const size_t N,const size_t L, const size_t M,const size_t J) {
return ((J*dim_M + M)*dim_L + L)*dim_N + N;
}
double operator()(size_t N,size_t L, size_t M, size_t J){
return data[multi_index(N,L,M,J)];
}
static void assign(size_t N,size_t L, size_t M, size_t J,double value){
data[multi_index(N,L,M,J)]=value;
}
};
int main()
{
double *instance;
T_4D<3,3,3,10,instance> T;
T.create();
return 0;
}
The compilation errors are:
./main.cpp: In function ‘int main()’:
./main.cpp:49:17: error: the value of ‘instance’ is not usable in a constant expression
T_4D<3,3,3,10,instance> T;
^
./main.cpp:48:11: note: ‘instance’ was not declared ‘constexpr’
double *instance;
^
./main.cpp:49:25: error: ‘instance’ is not a valid template argument because ‘instance’ is a variable, not the address of a variable
T_4D<3,3,3,10,instance> T;
^
./main.cpp:50:5: error: request for member ‘create’ in ‘T’, which is of non-class type ‘int’
T.create();
^
Makefile:197: recipe for target 'obj/main.o' failed
make: *** [obj/main.o] Error 1
If all of your dimensions are known at compile time, there is no need for you to allocate dynamic memory. Simply use:
std::aligned_storage_t<sizeof( T ) * SIZE, alignof( T )> data;
You don't even need to initialize anything since you're working with POD types. If you want to zero the memory out, just use this:
for ( std::size_t i = 0; i < SIZE; ++i )
*( reinterpret_cast<T*>( &data ) + i ) = 0;
This will be the most efficient implementation, since we use static contiguous memory. You'll have to implement proper indexing, but that's not too difficult.
Actually, just use T data[ SIZE ]; or std::array<T, SIZE> data.
Also, remove the double* template parameter, these cannot be changed, so it can't be used for your data.
Using double* data = NULL as a template parameter does not seem right. You can use a double* as a template parameter but you can't assign to it as you are doing with:
data=(double *)malloc(SIZE*sizeof(double));
You can remove that as a template parameter and make it a member variable of the class.
template <size_t dim_N=3,size_t dim_L=3,size_t dim_M=3,size_t dim_J=10>
struct T_4D {
double* data;
...
and then allocate memory for it in the constructor instead of in the static member function.
T_4D() : data(new double[SIZE])
{
memset(data, 0.0, SIZE*sizeof(*data));
}
Remember to follow The Rule of Three and The Rule of Five since you are allocating memory from the heap.
Then, main can simply be:
int main()
{
T_4D<3,3,3,10> T;
return 0;
}
Related
I am really at my wits end with trying to get pointers to work on c++. I have searched so many questions, but I just cant understand these things.
I am trying to do the equivalent of this python code in c++ :
class Node:
def __init__(self,isBase,channelList):
self.isBase = isBase
self.channelList = channelList
def getChannelList(self):
return self.channelList
def isBase(self):
return self.isBase
Channel list is the difficult bit. It is an array of integers.
I know that this will be passed as a pointer to my class declaration. I want to be able to store this in a class variable, and be able to get and set it on command.
The C++ Code is as follows:
#include "Arduino.h"
#include "Node.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
int *_channelList;
Node::Node(boolean isBase, int *channelList)
{
_isBase = isBase;
int i=0;
while(channelList[i]!='\0'){
_channelList[i] = channelList[i];
i++;
}
_channelList[i+1] = '\0';
}
boolean Node::isBase(){
return _isBase;
}
int* Node::getChannelList(){
return _channelList;
}
Justin Time's answer is the correct way to implement this in C++ (using arrays and vectors natively handled by C++)
I just have to add this solution, which is the correct way to implement what you tried to do in C (i.e. using char arrays).
There are two problems in your code
_channelList is NOT tied to the Node object, but is a somewhat static member.
_channelList is never allocated, so it points to nothing.
not a real problem, but usually '\0' is the string terminator. Ok, it maps to 0, but you should just use a 0 here
There are two solutions here. The first one is to give _channelList a fixed MAXIMUM size (maximum means that if the passed channelList is shorter you will get a shorter list, ok, but the allocated memory will still be the maximum one).
// File Node.h
#define MAXIMUM_CHANNELS 10
class Node {
public:
Node(boolean isBase, int *channelList);
boolean isBase();
int* getChannelList();
private:
int _channelList[MAXIMUM_CHANNELS + 1]; // Last one is the terminator
};
// File Node.cpp
include "Arduino.h"
#include "Node.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
Node::Node(boolean isBase, int *channelList)
{
_isBase = isBase;
int channelListLength;
// Get channel list lenght
for (channelListLength = 0; channelList[channelListLength] != 0; channelListLength++);
if (channelListLength > MAXIMUM_CHANNELS)
channelListLength = MAXIMUM_CHANNELS;
int i;
for (i = 0; i < channelListLength; i++)
_channelList[i] = channelList[i];
_channelList[channelListLength] = 0; // Enforce the last one to be a 0
}
boolean Node::isBase(){
return _isBase;
}
int* Node::getChannelList(){
return _channelList;
}
The second method dynamically allocates the memory for the array. You should, however, dispose it when you are done with the object (in the destructor). This means that if you create the Node variable you are ok (for instance, Node mynode;). If, however, you dynamically allocate it (with Node *p_mynode = new Node(); you will need to call a delete on it when you are done.
// File Node.h
class Node {
public:
Node(boolean isBase, int *channelList);
~Node(); // destructor (called at object destruction)
boolean isBase();
int* getChannelList();
private:
int *_channelList;
};
// File Node.cpp
include "Arduino.h"
#include "Node.h"
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
Node::Node(boolean isBase, int *channelList)
{
_isBase = isBase;
int channelListLength;
// Get channel list lenght
for (channelListLength = 0; channelList[channelListLength] != 0; channelListLength++);
_channelList = (int*)malloc((channelListLength+1)*sizeof(int));
if (_channelList != NULL)
{
int i;
for (i = 0; i <= channelListLength; i++)
_channelList[i] = channelList[i];
// No need to enforce the last one to be a 0
}
}
~Node()
{
free(_channelList);
}
boolean Node::isBase(){
return _isBase;
}
int* Node::getChannelList(){
return _channelList;
}
Note, however, that if the malloc fails you will have a NULL pointer. In theory it should not fail, unless you run out of ram...
Just one more thing. Using a 0-terminated int array is not a good idea, because if you have something like this { 15, 3, 0, 5, 10 } and then the terminator you will just get the first two numbers. It would be MUCH better to explicitely tell the array size (and save it in the object)
// File Node.h
class Node {
[...]
private:
int *_channelList;
int _channelListLength;
};
// File Node.cpp
Node::Node(boolean isBase, int *channelList, int channelListLength)
{
_isBase = isBase;
_channelListLength = channelListLength;
_channelList = (int*)malloc((_channelListLength)*sizeof(int));
if (_channelList != NULL)
{
int i;
for (i = 0; i <= _channelListLength; i++)
_channelList[i] = channelList[i];
}
}
...
int Node::getChannelListLength(){
return _channelListLength;
}
Assuming that channelList is null-terminated, and that _channelList is supposed to be a class member, you could try this:
#include <algorithm> // For std::copy().
// ...
template<size_t N> Node::Node(bool isBase, const int (&channelList)[N]) : _isBase(isBase)
{
std::copy(std::begin(channelList), std::end(channelList), std::begin(_channelList));
}
Unless I'm missing something, that should take a C-style int array of any size, and copy it into _channelList. If the passed array is larger than _channelList, it may cause issues. If possible, you would be better off using a std::array if the size is predetermined, or a std::vector if it isn't.
If the size is fixed:
#include <array>
#include <algorithm> // For std::copy() and std::fill().
const size_t _sz = [whatever];
// Simple way of setting size, but not the best. See below.
class Node
{
bool _isBase;
std::array<int, _sz> _channelList;
public:
Node(bool isBase, const int (&channelList)[_sz]);
Node(bool isBase, const std::array<int, _sz>& channelList);
// ...
};
/* Alternatively, you can code the size into the class as a magic number (not a good idea),
* or better yet, make it a template parameter for the class:
* template<size_t _sz> class Node
* {
* bool _isBase;
* std::array<int, _sz> _channelList;
*
* public:
* Node(/ * parameters * /);
*
* template<size_t N>
* Node(/ * parameters * /);
* // ...
* };
* When using the class, you would declare an instance as "Node<SIZE>", where "SIZE" is the
* desired size.
*
* Note that if you make the size a template parameter, and define the member functions
* outside of the class' definition, you have to put the same template at the start of each
* member function:
* template<size_t _sz> Node<_sz>::Node(/ * parameters * /)
* {
* // ...
* }
* This also applies to templated member functions, which will have two sets of template
* parameters.
* template<size_t _sz> template<size_t N> Node<_sz>::Node(/ * parameters * /)
* {
* // ...
* }
*/
// Constructor initialising from C array, if you need to work with preexisting code.
Node::Node(bool isBase, const int (&channelList)[_sz]) : _isBase(isBase)
{
std::copy(std::begin(channelList), std::end(channelList), std::begin(_channelList));
}
// Constructor using std::array.
Node::Node(bool isBase, const std::array<int, _sz>& channelList)
: _isBase(isBase), _channelList(channelList)
{
// Initialisation list handles everything.
}
// Note, however, that this will cause issues if the size of channelList doesn't
// necessarily match the size of _channelList. To solve this, we can change Node as
// follows:
// (Note that delegation requires a C++11-compatible compiler.)
#include <type_traits> // For std::integral_constant, std::true_type, and std::false_type.
class Node {
bool _isBase;
std::array<int, _sz> _channelList;
// Actual constructors (C-style array):
template<size_t N>
Node(std::true_type x, bool isBase, const int (&channelList)[N]);
template<size_t N>
Node(std::false_type x, bool isBase, const int (&channelList)[N]);
// Actual constructors (std::array):
template<size_t N>
Node(std::true_type x, bool isBase, const std::array<int, N>& channelList);
template<size_t N>
Node(std::false_type x, bool isBase, const std::array<int, N>& channelList);
public:
// Public constructors, delegate to one of the actual constructors.
// C-style array:
template<size_t N>
Node(bool isBase, const int (&channelList)[N]);
// std::array:
template<size_t N>
Node(bool isBase, const std::array<int, N>& channelList);
// ...
};
/* Now, these constructors are easy enough to make.
* I'll provide an example using C-style arrays. To make versions that take a
* std::array instead, change the parameter:
* const int (&channelList)[N]
* to:
* const std::array<int, N>& channelList
* The constructors should work properly with either kind of array.
*/
// Check if passed array is smaller than or equal to _sz, or if it's larger..
template<size_t N> Node::Node(bool isBase, const int (&channelList)[N])
: Node(std::integral_constant<bool, N <= _sz>{}, isBase, channelList) { }
// N is smaller than or equal to _sz.
template<size_t N> Node::Node(std::true_type x, bool isBase, const int (&channelList)[N])
: _isBase(isBase)
{
// Copy channelList into _channelList.
std::copy(std::begin(channelList), std::end(channelList), std::begin(_channelList));
// Fill empty space at the end of _channelList.
std::fill(&(_channelList[N]), std::end(_channelList), '\0');
}
// N is larger than _sz.
template<size_t N> Node::Node(std::false_type x, bool isBase, const int (&channelList)[N])
{
// Handle appropriately.
}
This should allow you to get the functionality you want. [Note that you can also use the above delegation, true_type, and false_type constructors to fill C-style arrays as well as std::arrays, if you need to use them.]
If the size isn't fixed:
#include <vector>
#include <algorithm>
class Node {
bool _isBase;
std::vector<int> _channelList;
public:
template<size_t N>
Node(bool isBase, const int (&channelList)[N]);
// ...
};
template<size_t N> Node::Node(bool isBase, const int (&channelList)[N]) : _isBase(isBase)
{
_channelList.assign(std::begin(channelList), std::end(channelList));
}
// You can also define a constructor that takes a std::array<int, N>, if you
// so desire. Again, the only change needed is the parameter itself.
As a vector's length can be changed at runtime, we can use vector::assign to allocate space and store the entirety of channelList.
Regardless of whether _channelList is stored as a C array, std::array, or std::vector, it's relatively easy to define getters and setters.
Getter (entire thing):
// All of the following use this class definition, with comments identifying which
// functions use which parts.
// Note that the trailing "const" in each getter signature indicates that the function
// cannot be used to modify the instance. It's optional, but useful to include.
class Node {
// Return C array (either way).
int _channelListC[_sz];
// Return std::array.
std::array<int, _sz> _channelListSArr;
// Return std::vector.
std::vector<int> _channelListSVec;
// Return C array the readable way.
typedef int _channelListC_t[_sz];
// C++11 alternative typedef:
using _channelListC_t = decltype(_channelList);
// The C++11 version is safer, as "decltype(_channelList)" won't break if you change
// _channelList's implementation.
// If you need to return the entire array, it may be a good idea to make this a public
// typedef, so it's easier & safer to declare a variable you can return it to.
public:
// Return C array the ugly way.
const int (&getChannelListCUgly() const)[_sz];
// Return C array the readable way.
const _channelListC_t& getChannelListCReadable() const;
// Return C array the readable C++11 way.
auto getChannelListCReadableCPP11() const -> const int(&)[_sz];
// Return std::array.
const std::array<int, _sz>& getChannelListSArr() const;
// Return std::vector.
const std::vector<int>& getChannelListSVec() const;
};
// Return C array:
/* Note that you can't return an array from a function. However, you can return a pointer
* or reference to an array, depending on whether you use * or & in the signature.
*/
// The ugly way:
const int (&Node::getChannelListCUgly() const)[_sz]
{
return _channelList;
}
// The readable way:
const Node::_channelListC_t& Node::getChannelListCReadable() const
{
return _channelList;
}
// The new readable way, as of C++11:
auto getChannelListCReadableCPP11() const -> const int(&)[_sz]
{
return _channelList;
}
// Return std::array:
const std::array<int, _sz>& Node::getChannelListSArr() const
{
return _channelList;
}
// Return std:;vector:
const std::vector<int>& getChannelListSVec() const
{
return _channelList;
}
Note that to my knowledge, a C-style array returned in this manner must be stored in a reference variable.
Node::_channelListC_t& arr = nodeInstance.getChannelListCUgly();
Getter (single element):
// C array or std::array:
int Node::getChannelListArrElement(int index) const
{
if (index < _sz)
{
// index is valid, return element.
return _channelList[index];
}
else
{
// index >= _sz, and is invalid.
// Handle accordingly.
}
}
// std::vector:
int Node::getChannelListVecElement(int index) const
{
if (index < _channelList.size())
{
// index is valid.
return _channelList[index];
}
else
{
// index is invalid.
// Handle accordingly.
}
}
You can define a setter for the entire thing using the constructors above. I would suggest using std::fill() to erase the contents of _channelList first, then copying the new array into _channelList. You can define a setter for single elements using the single-element getter as a basis.
Setter (entire thing):
// Array (either type):
// "CHANNEL_LIST_TYPE[N] channelList" is either "const int (&channelList)[N]" or
// "std::array<int, N>& channelList". Remember to replace it with the correct one in the
// actual code.
// Public function.
template<size_t N>
void Node::setChannelListArr(CHANNEL_LIST_TYPE[N] channelList)
{
setChannelListArr(std::integral_constant<bool, N <= _sz>{}, channelList);
}
// Private function, N <= _sz.
template<size_t N>
void Node::setChannelListArr(std::true_type x, CHANNEL_LIST_TYPE[N] channelList)
{
std::fill(std::begin(_channelList), std::end(_channelList), '\0');
std::copy(std::begin(channelList), std::end(channelList), std::begin(_channelList));
}
// Private function, N > _sz.
template<size_t N>
void Node::setChannelListArr(std::false_type x, CHANNEL_LIST_TYPE[N] channelList)
{
// channelList is too large. Handle appropriately.
}
// std::vector:
// "CHANNEL_LIST_TYPE[N]" is used as above, and should be replaced in your actual code.
// Also note that you can easily modify this function to accept another vector, by
// removing the template, making the parameter "const std::vector<int>& channelList", and
// using "channelList.size()" in place of "N" when calling resize().
template<size_t N>
void Node::setChannelListVec(CHANNEL_LIST_TYPE[N] channelList)
{
_channelList.resize(N); // Resize _channelList to have N elements.
std::fill(std::begin(_channelList), std::end(_channelList), '\0');
std::copy(std::begin(channelList), std::end(channelList), std::begin(_channelList));
}
Setter (single element):
// Array (either type):
void Node::setChannelListArrElement(int index, int value)
{
if (index < _sz)
{
_channelList[index] = value;
}
else
{
// index is invalid. Handle accordingly.
}
}
// std::vector:
void Node::setChannelListVecElement(int index, int value)
{
if (index < _channelList.size())
{
_channelList[index] = value;
}
else
{
// index is invalid. Handle accordingly.
}
}
// Alternative std::vector setter:
void Node::setChannelListVecElement2(int index, int value)
{
if (index >= _channelList.size())
{
// index is out of bounds. Resize vector to fit it.
_channelList.resize(index + 1, '\0');
}
// Modify element.
_channelList[index] = value;
}
Note that this answer assumes that channelList is null-terminated, as it appears to be. If channelList isn't null-terminated, but you want to stop filling _channelList at the first null element, then you'll have to do a bit more work, likely using your while loop.
You can find working examples of most of the above here. It's a bit of a mess, since it's just a quick program I used to test various things while typing up this answer.
[My apologies for any typoes and/or errors I may have missed. I believe I caught them, but there may still be some there.]
[Edit: Added a note about using fixed-size template constructors with C arrays. Added the C++11 trailing return type way of returning a reference to an array. Added a simple, working example.]
[Edit: Added an additional single-element setter for a vector.]
well i cant find how do this, basically its a variable union with params, basic idea, (writed as function)
Ex1
union Some (int le)
{
int i[le];
float f[le];
};
Ex2
union Some
{
int le;
int i[le];
float f[le];
};
obs this don't works D:
maybe a way to use an internal variable to set the lenght but don't works too.
Thx.
No, this is not possible: le would need to be known at compile-time.
One solution would be to use a templated union:
template <int N> union Some
{
int i[N];
float f[N];
};
N, of course, is compile-time evaluable.
Another solution is the arguably more succinct
typedef std::vector<std::pair<int, float>> Some;
or a similar solution based on std::array.
Depending on your use case you could try to simulate a union.
struct Some
{
//Order is important
private:
char* pData;
public:
int* const i;
float* const f;
public:
Some(size_t len)
:pData(new char[sizeof(int) < sizeof(float) ? sizeof(float) : sizeof(int)])
,i ((int*)pData)
,f ((float*)pData)
{
}
~Some()
{
delete[] pData;
}
Some(const Some&) = delete;
Some& operator=(const Some&) = delete;
};
Alternative solution using templates, unique_ptr and explicit casts:
//max_size_of<>: a recursive template struct to evaluate the
// maximum value of the sizeof function of all types passed as
// parameter
//The recursion is done by using the "value" of another
// specialization of max_size_of<> with less parameter types
template <typename T, typename...Args>
struct max_size_of
{
static const std::size_t value = std::max(sizeof(T), max_size_of<Args...>::value);
};
//Specialication for max_size_of<> as recursion stop
template <typename T>
struct max_size_of<T>
{
static const std::size_t value = sizeof(T);
};
//dataptr_auto_cast<>: a recursive template struct that
// introduces a virtual function "char* const data_ptr()"
// and an additional explicit cast operator for a pointer
// of the first type. Due to the recursion a cast operator
// for every type passed to the struct is created.
//Attention: types are not allowed to be duplicate
//The recursion is done by inheriting from of another
// specialization of dataptr_auto_cast<> with less parameter types
template <typename T, typename...Args>
struct dataptr_auto_cast : public dataptr_auto_cast<Args...>
{
virtual char* const data_ptr() const = 0; //This is needed by the cast operator
explicit operator T* const() const { return (T*)data_ptr(); } //make it explicit to avoid unwanted side effects (manual cast needed)
};
//Specialization of dataptr_auto_cast<> as recursion stop
template <typename T>
struct dataptr_auto_cast<T>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
//union_array<>: inherits from dataptr_auto_cast<> with the same
// template parameters. Also has a static const member "blockSize"
// that indicates the size of the largest datatype passed as parameter
// "blockSize" is used to determine the space needed to store "size"
// elements.
template <typename...Args>
struct union_array : public dataptr_auto_cast<Args...>
{
static const size_t blockSize = max_size_of<Args...>::value;
private:
std::unique_ptr<char[]> m_pData; //std::unique_ptr automatically deletes the memory it points to on destruction
size_t m_size; //The size/no. of elements
public:
//Create a new array to store "size" elements
union_array(size_t size)
:m_pData(new char[size*blockSize])
,m_size(size)
{
}
//Copy constructor
union_array(const union_array<Args...>& other)
:m_pData(new char[other.m_size*blockSize])
,m_size(other.m_size)
{
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
//Move constructor
union_array(union_array<Args...>&& other)
:m_pData(std::move(other.m_pData))
,m_size(std::move(other.m_size))
{
}
union_array& operator=(const union_array<Args...>& other)
{
m_pData = new char[other.m_size*blockSize];
m_size = other.m_size;
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
union_array& operator=(union_array<Args...>&& other)
{
m_pData = std::move(other.m_pData);
m_size = std::move(other.m_size);
}
~union_array() = default;
size_t size() const
{
return m_size;
}
//Implementation of dataptr_auto_cast<>::data_ptr
virtual char* const data_ptr() const override
{
return m_pData.get();
}
};
int main()
{
auto a = union_array<int, char, float, double>(5); //Create a new union_array object with enough space to store either 5 int, 5 char, 5 float or 5 double values.
((int*)a)[3] = 3; //Use as int array
auto b = a; //copy
((int*)b)[3] = 1; //Change a value
auto c = std::move(a);// move a to c, a is invalid beyond this point
// std::cout << ((int*)a)[3] << std::endl; //This will crash as a is invalid due to the move
std::cout << ((int*)b)[3] << std::endl; //prints "1"
std::cout << ((int*)c)[3] << std::endl; //prints "3"
}
Explanation
template <typename T, typename...Args>
struct max_size_of
{
static const std::size_t value = std::max(sizeof(T), max_size_of<Args...>::value);
};
template <typename T>
struct max_size_of<T>
{
static const std::size_t value = sizeof(T);
};
max_size_of<> is used to get the largest sizeof() value of all types passed as template paremeters.
Let's have a look at the simple case first.
- max_size_of<char>::value: value will be set to sizeof(char).
- max_size_of<int>::value: value will be set to sizeof(int).
- and so on
If you put in more than one type it will evaluate to the maximum of the sizeof of these types.
For 2 types this would look like this: max_size_of<char, int>::value: value will be set to std::max(sizeof(char), max_size_of<int>::value).
As described above max_size_of<int>::value is the same as sizeof(int), so max_size_of<char, int>::value is the same as std::max(sizeof(char), sizeof(int)) which is the same as sizeof(int).
template <typename T, typename...Args>
struct dataptr_auto_cast : public dataptr_auto_cast<Args...>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
template <typename T>
struct dataptr_auto_cast<T>
{
virtual char* const data_ptr() const = 0;
explicit operator T* const() const { return (T*)data_ptr(); }
};
dataptr_auto_cast<> is what we use as a simple abstract base class.
It forces us to implement a function char* const data_ptr() const in the final class (which will be union_array).
Let's just assume that the class is not abstract and use the simple version dataptr_auto_cast<T>:
The class implements a operator function that returns a pointer of the type of the passed template parameter.
dataptr_auto_cast<int> has a function explicit operator int* const() const;
The function provides access to data provided by the derived class through the data_ptr()function and casts it to type T* const.
The const is so that the pointer isn't altered accidentially and the explicit keyword is used to avoid unwanted implicit casts.
As you can see there are 2 versions of dataptr_auto_cast<>. One with 1 template paremeter (which we just looked at) and one with multiple template paremeters.
The definition is quite similar with the exception that the multiple parameters one inherits dataptr_auto_cast with one (the first) template parameter less.
So dataptr_auto_cast<int, char> has a function explicit operator int* const() const; and inherits dataptr_auto_cast<char> which has a function explicit operator char* const() const;.
As you can see there is one cast operator function implemented with each type you pass.
There is only one exception and that is passing the same template parameter twice.
This would lead in the same operator function being defined twice within the same class which doesn't work.
For this use case, using this as a base class for the union_array, this shouldn't matter.
Now that these two are clear let's look at the actual code for union_array:
template <typename...Args>
struct union_array : public dataptr_auto_cast<Args...>
{
static const size_t blockSize = max_size_of<Args...>::value;
private:
std::unique_ptr<char[]> m_pData;
size_t m_size;
public:
//Create a new array to store "size" elements
union_array(size_t size)
:m_pData(new char[size*blockSize])
,m_size(size)
{
}
//Copy constructor
union_array(const union_array<Args...>& other)
:m_pData(new char[other.m_size*blockSize])
,m_size(other.m_size)
{
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
//Move constructor
union_array(union_array<Args...>&& other)
:m_pData(std::move(other.m_pData))
,m_size(std::move(other.m_size))
{
}
union_array& operator=(const union_array<Args...>& other)
{
m_pData = new char[other.m_size*blockSize];
m_size = other.m_size;
memcpy(m_pData.get(), other.m_pData.get(), other.m_size);
}
union_array& operator=(union_array<Args...>&& other)
{
m_pData = std::move(other.m_pData);
m_size = std::move(other.m_size);
}
~union_array() = default;
size_t size() const
{
return m_size;
}
virtual char* const data_ptr() const override
{
return m_pData.get();
}
};
As you can see union_array<> inherits from dataptr_auto_cast<> using the same template arguments.
So this gives us a cast operator for every type passed as template paremeter to union_array<>.
Also at the end of union_array<> you can see that the char* const data_ptr() const function is implemented (the abstract function from dataptr_auto_cast<>).
The next interesting thing to see is static const size_t blockSize which is initilialized with the maximum sizeof value of the template paremeters to union_array<>.
To get this value the max_size_of is used as described above.
The class uses std::unique_ptr<char[]> as data storage, as std::unique_ptr automatically will delete the space for us, once the class is destroyed.
Also std::unique_ptr is capable of move semantics, which is used in the move assign operator function and the move constructor.
A "normal" copy assign operator function and a copy constructor are also included and copy the memory accordingly.
The class has a constructor union_array(size_t size) which takes the number of elements the union_array should be able to hold.
Multiplying this value with blockSize gives us the space needed to store exactly size elements of the largest template type.
Last but not least there is an access method to ask for the size() if needed.
C++ requires that the size of a type be known at compile time.
The size of a block of data need not be known, but all types have known sizes.
There are three ways around it.
I'll ignore the union part for now. Imagine if you wanted:
struct some (int how_many) {
int data[how_many];
};
as the union part adds complexity which can be dealt with separately.
First, instead of storing the data as part of the type, you can store pointers/references/etc to the data.
struct some {
std::vector<int> data;
explicit some( size_t how_many ):data(how_many) {};
some( some&& ) = default;
some& operator=( some&& ) = default;
some( some const& ) = default;
some& operator=( some const& ) = default;
some() = default;
~some() = default;
};
here we store the data in a std::vector -- a dynamic array. We default copy/move/construct/destruct operations (explicitly -- because it makes it clearer), and the right thing happens.
Instead of a vector we can use a unique_ptr:
struct some {
std::unique_ptr<int[]> data;
explicit some( size_t how_many ):data(new int[how_many]) {};
some( some&& ) = default;
some& operator=( some&& ) = default;
some() = default;
~some() = default;
};
this blocks copying of the structure, but the structure goes from being size of 3 pointers to being size of 1 in a typical std implementation. We lose the ability to easily resize after the fact, and copy without writing the code ourselves.
The next approach is to template it.
template<std::size_t N>
struct some {
int data[N];
};
this, however, requires that the size of the structure be known at compile-time, and some<2> and some<3> are 'unrelated types' (barring template pattern matching). So it has downsides.
A final approach is C-like. Here we rely on the fact that data can be variable in size, even if types are not.
struct some {
int data[1]; // or `0` in some compilers as an extension
};
some* make_some( std::size_t n ) {
Assert(n >= 1); // unless we did `data[0]` above
char* buff = new some[(n-1)*sizeof(int) + sizeof(some)]; // note: alignment issues on some platforms?
return new(buff) some(); // placement new
};
where we allocate a buffer for some of variable size. Access to the buffer via data[13] is practically legal, and probably actually so as well.
This technique is used in C to create structures of variable size.
For the union part, you'll want to create a buffer of char with the right size std::max(sizeof(float), sizeof(int))*N, and expose functions:
char* data(); // returns a pointer to the start of the buffer
int* i() { return reinterpret_cast<int*>(data()); }
float* f() { return reinterpret_cast<float*>(data()); }
you may also need to properly initialize the data as the proper type; in theory, a char buffer of '\0's may not correspond to defined float values or ints that are zero.
I would like to suggest a different approach: Instead of tying the number of elements to the union, tie it outside:
union Some
{
int i;
float f;
};
Some *get_Some(int le) { return new Some[le]; }
Don't forget to delete[] the return value of get_Some... Or use smart pointers:
std::unique_ptr<Some[]> get_Some(int le)
{ return std::make_unique<Some[]>(le); }
You can even create a Some_Manager:
struct Some_Manager
{
union Some
{
int i;
float f;
};
Some_Manager(int le) :
m_le{le},
m_some{std::make_unique<Some[]>(le)}
{}
// ... getters and setters...
int count() const { return m_le; }
Some &operator[](int le) { return m_some[le]; }
private:
int m_le{};
std::unique_ptr<Some[]> m_some;
};
Take a look at the Live example.
It's not possible to declare a structure with dynamic sizes as you are trying to do, the size must be specified at run time or you will have to use higher-level abstractions to manage a dynamic pool of memory at run time.
Also, in your second example, you include le in the union. If what you were trying to do were possible, it would cause le to overlap with the first value of i and f.
As was mentioned before, you could do this with templating if the size is known at compile time:
#include <cstdlib>
template<size_t Sz>
union U {
int i[Sz];
float f[Sz];
};
int main() {
U<30> u;
u.i[0] = 0;
u.f[1] = 1.0;
}
http://ideone.com/gG9egD
If you want dynamic size, you're beginning to reach the realm where it would be better to use something like std::vector.
#include <vector>
#include <iostream>
union U {
int i;
float f;
};
int main() {
std::vector<U> vec;
vec.resize(32);
vec[0].i = 0;
vec[1].f = 42.0;
// But there is no way to tell whether a given element is
// supposed to be an int or a float:
// vec[1] was populated via the 'f' option of the union:
std::cout << "vec[1].i = " << vec[1].i << '\n';
}
http://ideone.com/gjTCuZ
#include <iostream>
#include <string>
using namespace std;
template <class T> int IsSubArr(T& a, int a_len, T& b, int b_len)
{
int i,j;
bool found;
int k;
T& s=a,l=b;
int s_len = (a_len < b_len) ? a_len : b_len; // find the small array length
if (s_len == a_len) // check to set pointers to small and long array
{
s = a;
l = b;
}
else
{
s = b;
l = a;
}
for (i = 0; i <= a_len-s_len; i++) //loop on long array
{
found = true;
k=i;
for (j=0; j<s_len; j++) // loop on sub array
{
if (s[j] != l[i])
{
found = false;
break;
}
k++;
}
}
if (found)
return i;
else
return -1;
}
/******* main program to test templates ****/
int main()
{
int array[5] = {9,4,6,2,1};
int alen = 5;
int sub_arr[3] = {6,2,1};
int slen = 3;
int index= 0;
index = IsSubArr(array,alen,sub_arr,slen);
cout << "\n\n Place of sub array in long array: " << index;
cout << endl;
return 0;
}
for this line of code:
index = IsSubArr(array,alen,sub_arr,slen);
i get error:
Error 1 error C2782: 'int IsSubArr(T &,int,T &,int)' : template parameter 'T' is ambiguous
please help to resolve this issue ?
Since array[a] and array[b] where a != b are 2 different types, you'll need 2 type templates args.
A work around would be to use pointers.
+ template <class T> int IsSubArr(T* a, int a_len, T* b, int b_len)
+ T* s = a; T*l = b;
You defined the first and the third parameters as references
template <class T> int IsSubArr(T& a, int a_len, T& b, int b_len)
^^^^ ^^^^
and pass as arguments for these parameters two arrays with different types
int array[5] = {9,4,6,2,1};
int sub_arr[3] = {6,2,1};
//...
index = IsSubArr(array,alen,sub_arr,slen);
^^^^^ ^^^^^^^
The first argument has type int[5] and the third argument has type int[3]
So the compiler is unable to deduce the referenced type T.
If you are going to use arrays with the function then you could declare it like
template <class T, size_t N1, size_t N2>
int IsSubArr( T ( &a )[N1], T ( &b )[N2] );
Or you could use pointers instead of the references to arrays
template <class T> int IsSubArr( T *a, size_t a_len, T *b, size_t b_len );
Take into account that this declaration within the function
T& s=a,l=b;
is also wrong. It is equivalent to the following declarations
T& s=a;
T l=b;
That is the first declaration declares a reference to an array while the second declaration declares an array and tries to initialize it with another array. However arrays do not have a copy constructor and the compiler will issue one more error. And you may not reassign a reference.
You should know that there is standard algorithm std::search declared in header <algorithm> that can do the job you want to do with your function.
It's because array and sub_arr are two different types. array is of type int[5] while sub_arr is of type int[3]. The array dimensions are part of the type.
Either change the function to use two different templates arguments, one for each array, or use pointer (e.g. T*)
There's also another error, that you will continue to have if you keep using arrays and two different template arguments, and that is that you can't change references. Once you have assigned to the variable s and l in the function, those can't be made to reference anything else. The latter assignments of the s and l variables will fail because there you try to assign the arrays to each other, which you can not do, you can only copy arrays.
If you use pointers instead, then this won't be a problem.
I want to write copy constructor for a template class. I have this class:
template<int C>
class Word {
array<int, C> bitCells; //init with zeros
int size;
public:
//constructor fill with zeros
Word<C>() {
//bitCells = new array<int,C>;
for (int i = 0; i < C; i++) {
bitCells[i] = 0;
}
size = C;
}
Word<C>(const Word<C>& copyObg) {
size=copyObg.getSize();
bitCells=copyObg.bitCells;
}
}
I have errors with the copy constructor, on the line of intilizeing the size, I get:
"Multiple markers at this line
- passing 'const Word<16>' as 'this' argument of 'int Word::getSize() [with int C = 16]' discards qualifiers [-
fpermissive]
- Invalid arguments ' Candidates are: int getSize() '"
what is wrong with this ?
thank you
I'd write the class like this:
template <std::size_t N>
class Word
{
std::array<int, N> bit_cells_;
public:
static constexpr std::size_t size = N;
Word() : bit_cells_{} {}
// public functions
};
Note:
No need for a dynamic size, since it's part of the type.
No need for special member functions, since the implicitly defined ones are fine.
Initialize the member array to zero via the constructor-initializer-list.
Template parameter is unsigned, since it represents a count.
What's wrong is that your getSize() is not declared const. Make it so:
int getSize() const { return size; }
I'm having trouble with nontype(int variable) template parameter.
Why can't I pass a constant int variable to a function and let the function instantiate the template?
template<int size>
class MyTemplate
{
// do something with size
};
void run(const int j)
{
MyTemplate<j> b; // not fine
}
void main()
{
const int i = 3;
MyTemplate<i> a; // fine;
run(i); // not fine
}
not fine : compiler says, error: 'j' cannot appear in constant-expression
EDIT
This is what I ended up with.
Maybe someone might use it, someone might suggest better way.
enum PRE_SIZE
{
PRE_SIZE_256 = 256,
PRE_SIZE_512 = 512,
PRE_SIZE_1024 = 1024,
};
template<int size>
class SizedPool : public Singleton< SizedPool<size> >
{
public:
SizedPool()
: mPool(size)
{
}
void* Malloc()
{
return mPool.malloc();
}
void Free(void* memoryPtr)
{
mPool.free(memoryPtr);
}
private:
boost::pool<> mPool;
};
template<int size>
void* SizedPoolMalloc()
{
return SizedPool<size>::GetInstance()->Malloc();
}
template<int size>
void SizedPoolFree(void* memoryPtr)
{
SizedPool<size>::GetInstance()->Free(memoryPtr);
}
void* SizedPoolMalloc(int size)
{
if (size <= PRE_SIZE_256)
return SizedPoolMalloc<PRE_SIZE_256>();
else if (size <= PRE_SIZE_512)
return SizedPoolMalloc<PRE_SIZE_512>();
}
void toRun(const int j)
{
SizedPoolMalloc(j);
}
void Test17()
{
const int i = 3;
toRun(i);
}
Because non-type template parameters require values at compile-time. Remember that templates are a compile-time mechanism; templates do not exist in the final executable. Also remember that functions and the passing of arguments to functions are runtime mechanisms. The value of the j parameter in run() will not be known until the program actually runs and invokes the run() function, well past after the compilation stage.
void run(const int j)
{
// The compiler can't know what j is until the program actually runs!
MyTemplate<j> b;
}
const int i = 3;
run(i);
That's why the compiler complains says "'j' cannot appear in constant-expression".
On the other hand, this is fine because the value of i is known at compile-time.
const int i = 3;
// The compiler knows i has the value 3 at this point,
// so we can actually compile this.
MyTemplate<i> a;
You can pass compile-time values to run-time constructs, but not the other way around.
However, you can have your run() function accept a non-type template parameter the same way your MyTemplate template class accepts a non-type template parameter:
template<int j>
void run()
{
MyTemplate<j> b;
}
const int i = 3;
run<i>();
Basically, C++ has two kinds of constants:
const int a = 5;
MyTemplate<a> foo; // OK
const int b = rand();
MyTemplate<b> foo; // Not OK.
The first example is a compile-time constant. In C++ standard speak, it's an Integral Constant Expression (ICE). The second example is a run-time constant. It has the same C++ type (const int) but it's not an ICE.
Your function void run(const int j) is a run-time constant. You could even pass in user input. Therefore it's not a valid template argument.
The reason for the rule is that the compiler must generate code based on the template argument value. It can't do so if it doesn't have a compile-time constant.
Because j should be known at compile time. In your example it is not.