Dynamic array inside of Class template - c++11

i have want to make template class Vector , parameters should be Type and length of an dynamic array thats in it.
template < class Type, int length >
class Vektor
{
public:
int Count;
int CurrentPos;
Type* Beginning = new Type[count];
int LastAtUse=0;
Vektor()
{
Count = length;
}
void PushBack(Type A)
{
Beginning[LastAtUse]=A;
LastAtUse++;
}
void insert(Type A, int position)
{
Beginning[position] = A;
}
};
I tried to test it in main and am getting an error:
error C2440: 'initializing' : cannot convert from 'iterator_traits<_Iter>::difference_type (__cdecl *)(_InIt,_InIt,const _Ty &)' to 'unsigned int'
Can you help me find what I'm doing wrong ?

Here:
Type* Beginning = new Type[count];
^
you have Count, not count
also, Count is not yet set when your new executes, you should move it to constructor here:
Vektor()
{
Count = length;
Beginning = new Type[Count];
}

Related

How to pass Comparator to user define Templeted class?

I want to create a generalized heap data structure, and facing an issue with passing template comparator.
template<typename T, typename C = less<T> > class Heap{
vector<T> *heap;
public:
Heap(vector<T> *arr){
heap = new vector<T> (arr->begin(), arr->end());
build_heap();
}
void build_heap(){
size_t n = heap->size();
for (size_t i=(n-1)/2; i>=0; i--){
shiftDown(i);
}
}
void shiftDown(size_t i){ /// heap logic
while(i < heap->size()){
size_t child = 2*i+1;
// int min_ind = 2*i+1;
if(child >= heap->size())
return;
if(child+1 < heap->size()){
if( C(heap->at(child+1),heap->at(child)) ){ // <----- using C as comparator
child++;
}
}
if( C(heap->at(child), heap->at(i)) ){ // <----- using C as comparator
swap(heap->at(child), heap->at(i));
i = child;
}
else
break;
}
}
};
int main(){
vector<int> v={8,7,6,5,4,3,2,1};
Heap<int, less<int> > heap(&v);
}
error
heap.cpp: In instantiation of ‘void Heap<T, C>::shiftDown(size_t) [with T = int; C = std::less<int>; size_t = long unsigned int]’:
heap.cpp:15:4: required from ‘void Heap<T, C>::build_heap() [with T = int; C = std::less<int>]’
heap.cpp:10:3: required from ‘Heap<T, C>::Heap(std::vector<_Tp>*) [with T = int; C = std::less<int>]’
heap.cpp:49:34: required from here
heap.cpp:32:9: error: no matching function for call to ‘std::less<int>::less(__gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&, __gnu_cxx::__alloc_traits<std::allocator<int>, int>::value_type&)’
32 | if( C(heap->at(child+1),heap->at(child)) ){
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
...
detailed error
i'm following same syntex of declaration as stl c++ do, still i'm getting error. please help me out.
template<typename T, typename C = less<T> > class Heap;
any help or pointer to help is appreciated. thank you.
template<class T>
class Comparator{
bool operator()(const T &a, const T &b){
...
// returns logic
}
}
template<class T, class Comp >
class AnyClass{
public:
...
void function(){
// code ...
Comp<T>()(obj1, obj2);
}
...
}
calling sytex :
...
AnyClass *obj = new AnyClass<Type , Comparator>();
obj.function()
...
passing Comparator to templated class and when we need to compare objects
we create a functional object and call operator() with args to compare.
In question, that object is less<int>.
Comp<T>()(obj1, obj2);

Accessing Base class variable inside Derived class

I have a public inheritance, Derived struct inheriting from Base. The Base has a data member int i initialized to 5.
Now I have two codes.
Code 1 : Compiles fine
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = i; // Derived class able to use variable i from Base
Derived(){
i = 10; // Constructor of Derived able to access i from Base
}
};
int main()
{
Derived dobj;
cout << dobj.i;
return 0;
}
Code 2 : Gives error
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = i; //Still works
i = 10; // Error here " main.cpp:15:3: error: ‘i’ does not name a type"
Derived() = default;
};
int main()
{
Derived dobj;
cout<<dobj.i;
return 0;
}
Why is it that i can be used to assign and be assigned inside constructor body (as in code 1), but not used directly in Derived class (as in code 2). Also what does the error mean?
I was under the impression that the scope of Derived is nested inside Base, so shouldn't it be able to see the data members inside Base scope?
This has nothing to do with base and derived classes but with scope. Your code is illegal for the same reason that this code is illegal:
struct X
{
int i;
i = 20; // error
};
https://godbolt.org/z/60zPb-
int i; or int i = 10; are declarations. i = 20; is a statement. Statements can only appear in function bodies, not at class (or namespace) scope.

Can a method of an class (in a shared_ptr) be tied to a static function in a traits class?

Historically, I've been using trait classes to hold information and apply that into a "generic" function that runs the same "algorithm." Only differed by the trait class. For example: https://onlinegdb.com/ryUo7WRmN
enum selector { SELECTOR1, SELECTOR2, SELECTOR3, };
// declaration
template < selector T> struct example_trait;
template<> struct example_trait<SELECTOR1> {
static constexpr size_t member_var = 3;
static size_t do_something() { return 0; }
};
template<> struct example_trait<SELECTOR2> {
static constexpr size_t member_var = 5;
static size_t do_something() { return 0; }
};
// pretend this is doing something useful but common
template < selector T, typename TT = example_trait<T> >
void function() {
std::cout << TT::member_var << std::endl;
std::cout << TT::do_something() << std::endl;
}
int main()
{
function<SELECTOR1>();
function<SELECTOR2>();
return 0;
}
I'm not sure how to create "generic" algorithms this when dealing with polymorphic classes.
For example: https://onlinegdb.com/S1hFLGC7V
Below I have created an inherited class hierarchy. In this example I have a base catch-all example that defaults all the parameters to something (0 in this case). And then each derived class sets overrides specific methods.
#include <iostream>
#include <memory>
#include <type_traits>
#include <assert.h>
using namespace std;
struct Base {
virtual int get_thing_one() {
return 0;
}
virtual int get_thing_two() {
return 0;
}
virtual int get_thing_three() {
return 0;
}
virtual int get_thing_four() {
return 0;
}
};
struct A : public Base {
virtual int get_thing_one() override {
return 1;
}
virtual int get_thing_three() override {
return 3;
}
};
struct B : public Base {
virtual int get_thing_one() override {
return 2;
}
virtual int get_thing_four() override{
return 4;
}
};
Here I created a simple factory, not elegant but for illustrative purposes
// example simple factory
std::shared_ptr<Base> get_class(const int input) {
switch(input)
{
case 0:
return std::shared_ptr<Base>(std::make_shared<A>());
break;
case 1:
return std::shared_ptr<Base>(std::make_shared<B>());
break;
default:
assert(false);
break;
}
}
So this is the class of interest. It is a class does "something" with the data from the classes above. The methods below are a simple addition example but imagine a more complicated algorithm that is very similar for every method.
// class that uses the shared_ptr
class setter {
private:
std::shared_ptr<Base> l_ptr;
public:
setter(const std::shared_ptr<Base>& input):l_ptr(input)
{}
int get_thing_a()
{
return l_ptr->get_thing_one() + l_ptr->get_thing_two();
}
int get_thing_b()
{
return l_ptr->get_thing_three() + l_ptr->get_thing_four();
}
};
int main()
{
constexpr int select = 0;
std::shared_ptr<Base> example = get_class(select);
setter l_setter(example);
std::cout << l_setter.get_thing_a() << std::endl;
std::cout << l_setter.get_thing_b() << std::endl;
return 0;
}
How can I make the "boilerplate" inside the setter class more generic? I can't use traits as I did in the example above because I can't tie static functions with an object. So is there a way to make the boilerplate example more common?
Somewhere along the lines of having a selector, say
enum thing_select { THINGA, THINGB, };
template < thing_select T >
struct thing_traits;
template <>
struct thing_traits<THINGA>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_one' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_two' method
}
template <>
struct thing_traits<THINGB>
{
static int first_function() --> somehow tied to shared_ptr<Base> 'thing_three' method
static int second_function() --> somehow tied to shared_ptr<Base> 'thing_four' method
}
// generic function I'd like to create
template < thing_select T, typename TT = thing_traits<T> >
int perform_action(...)
{
return TT::first_function(..) + TT::second_function(..);
}
I ideally would like to modify the class above to something along the lines of
// Inside setter class further above
int get_thing_a()
{
return perform_action<THINGA>(...);
}
int get_thing_b()
{
return perform_action<THINGB>(...);
}
The answer is, maybe I can't, and I need to pass int the shared_ptr as a parameter and call the specific methods I need instead of trying to tie a shared_ptr method to a static function (in hindsight, that doesn't sound like a good idea...but I wanted to bounce my idea)
Whoever makes the actual call will need a reference of the object, one way or the other. Therefore, assuming you want perform_action to perform the actual call, you will have to pass the parameter.
Now, if you really want to store which function of Base to call as a static in thing_traits without passing a parameter, you can leverage pointer to member functions:
template <>
struct thing_traits<THINGA>
{
static constexpr int (Base::*first_function)() = &Base::get_thing_one;
...
}
template < thing_select T, typename TT = thing_traits<T>>
int perform_action(Base & b)
{
return (b.*TT::first_function)() + ...;
}
You can also play instead with returning a function object that does the call for you (and the inner function takes the parameter).
It all depends on who you need to make the call and what information/dependencies you assume you have available in each class/template.

How to properly create template object of type T i.e. T result = T();

Hi I am trying to create an object of type T where T is a pointer via the use of T result = T(). But instead of calling the constructor it simply returns a null pointer.
Here is an example of some affected code:
template <class T>
T readBlockchain(std::ifstream* stream) {
T result = T(); // Result is null after this
decltype(result->getLastBlock()) blkPtr = result->getLastBlock();
auto blk = *blkPtr;
decltype(result->getLastBlock()) lastBlock = &readBlock<decltype(blk)>(stream);
if(!lastBlock->verify())
return nullptr;
unsigned long count = *readUnsignedLong(stream);
unsigned long orphanCount = *readUnsignedLong(stream);
std::map<std::string, decltype(blk)> blocks = std::map<std::string, decltype(blk)>();
for(int i = 0; i < count - 1; i++){
decltype(blk) block = readBlock<decltype(blk)>(stream);
if(!block.verify())
return nullptr;
blocks.insert(std::make_pair(block.getHash(), block));
}
std::vector<Blockchain<decltype(blk)>*> orphanedChains = std::vector<Blockchain<decltype(blk)>*>();
for(int i = 0; i < orphanCount - 1; i++){
Blockchain<decltype(blk)>* orphan = &readOrphanedChain<Blockchain<decltype(blk)>>(stream);
orphanedChains.push_back(orphan);
}
result->setLastBlock(lastBlock);
result->setCount(count);
result->setOrphanCount(orphanCount);
result->setBlocks(blocks);
result->setOrphanedChains(orphanedChains);
return result;
}
If my understanding is correct. In order to generalize your readBlockchain correctly, you would want when T is a pointer to create a new object of T in the heap and when T is a concrete type to create a regular T object by calling the constructor of T. One solution would be to use the following specialization construct.
template<typename T>
struct CreateNew {
template<typename... Args>
static T apply(Args&&... args) { return T(std::forward<Args>(args)...); }
};
template<typename T>
struct CreateNew<T*> {
template<typename... Args>
static decltype(auto) apply(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); }
};
That is, you could create a template class that takes a template argument T along with a specialization of that template class for pointers of type T*. Inside the primary template (e.g., static member function apply) you'll create objects of type T by calling the constructor of class T and inside the specialization you'll create heap objects of T* (Notice that in the specialization I return a std::unique_ptr<T*> for convenience).
Thus, your readBlockChain template function would become:
template <class T>
decltype(auto) readBlockchain(std::ifstream* stream) {
auto result = CreateNew<T>::apply(/* T constructor arguments */);
...
return result;
}
Live Demo

Deserialize Protocol Buffers using boost::mpl

I create my RPC Protocol with PB like:
enum EMessages {
E_MSG_METHOD_CONNECT = 0x8001,
E_MSG_EVENT_CONNECT = 0xA001,
...
}
struct MsgHeader {
required int32 sessionRef = 1;
required int32 transactionId = 2;
required int32 status = 3;
}
struct MSG_METHOD_CONNECT {
optional Messages opCode = 1 [default = E_MSG_METHOD_CONNECT];
required MsgHeader header = 2;
.. other fields ..
}
Now, I defined an interface and a template class to add a level of indirection:
class IMessage {
virtual INT getOpCode() = 0;
virtual STRING getName() = 0;
virtual size_t getSize() = 0;
virtual INT SerializeToString(STRING& out) = 0;
virtual INT ParseFromString(STRING& in) = 0;
....
}
template<class MESSAGE>
class IMessageImpl : public IMessage {
protected:
MESSAGE m_Message; ///< The Message Implementation
public:
virtual MESSAGE& getMessage() = 0;
};
And I will use it as:
IMessageImpl<MSG_METHOD_CONNECT> MsgConnect;
Now, when I receive the data from an endpoint I need, of course, to deserialize it according with the message opCode.
Reading this article I'm thinking to use a type map like boost::mpl::map but, since I never use it, I'm searching for some suggestions.
<< ------------------------ [EDIT] ------------------------ >>
Regarding the code above, I try to code it in the following way:
template<class MESSAGE>
class PBMessage : public IMessageImpl<MESSAGE>
{
public:
PBMessage() {};
/* ... other methods ... */
};
// Map of types. The key is the Message opCode
typedef typename mpl::map< mpl::pair<mpl::int_[100], PBMessage<MSG_METHOD_CONNECT> >,
mpl::pair<mpl::int_[101], PBMessage<MSG_EVENT_CONNECT> >,
> TMessageMap;
// The Message type
template < typename MessageMap, int opCode >
typedef typename mpl::at<MessageMap, mpl::int_<opCode> >::type::value TMessage;
And, to create a message from a received buffer I try to code (take it as pseudo-code):
class PBMessageFactory : public IMessageFactory {
public:
IMessage* createMessage(CHAR* buff, UINT size) {
int opCode = buff[0];
TMessage<TMessageMap, opCode> msg;
msg.ParseFromString( STRING(buff) );
}
};
But with no success...Is there someone could give me some suggestions how to retrieve types from a mpl::map?
Thanks,
Daniele.

Resources