Im trying to do a sort for the biggest to the lowest
my Math Vector inherit from Vector
now the Problem is i can't see the inhert function (see below &&&&&)
template <class T>
class Vector
{
protected:
T* Array;
int Size;
int Capacity;
public:
Vector();
Vector(Vector<T>& Copy_Array);
T operator=(const T* Element);
void operator=(const T Element);
T* operator[](const int Index) const;
ostream& operator<<(const Vector<T>& Print_Elements);
void Insert(T Element);/*Push*/
void ReSize(const int New_Size);
T* Pop();
void Set_size(int New_Size);
void Set_Capacity(int New_Capacity);
int Get_Size() const;
int Get_Capacity() const;
T* Top() const;
~Vector();
};
is this the right way to inherit just the function ofcurse(protected)
template<class T>
class MathVector:public Vector<T>/*<- form template to tamplate*/
{
public:
void Sort(const int Direction);
};
&&&&&&/* i can't see the public mathods of vector*/&&&&&&
template<class T>
void MathVector<T>::Sort(const int Direction)
{
this-> &&&&&&/* i can't see the public mathods of vector*/&&&&&&
};
Yes, it is the right way to inherit from your Vector<T>. And to use the public methods write for example
template<class T>
void MathVector<T>::Sort(const int Direction)
{
Vector<T>::yourNonPrivateMethod();
auto test = Vector<T>::yourNonPrivateMember;
};
You may also declare them by using in the header file:
using Vector<T>::yourNonPrivateMethod;
EDIT
Here a simplified example:
#include <iostream>
template<typename T> class Base
{
public:
Base() : member( static_cast<T>( 0 ) ) {};
virtual ~Base() = default;
T member;
void baseMemberFunction()
{
std::cout << "Base<T>::memberFunction()" << std::endl;
}
void anotherBaseMemberFunction()
{
std::cout << "Base<T>::anotherBaseMemberFunction()" << std::endl;
}
};
template<typename T> class Derived : public Base<T>
{
public:
Derived() : Base<T>(), member(1) {}
T member;
using Base<T>::anotherBaseMemberFunction;
void derivedMemberFunction()
{
std::cout << "Derived<T>::derivedMemberFunction()" << std::endl;
Base<T>::baseMemberFunction();
anotherBaseMemberFunction();
std::cout << "Derived<T>::member = " << member << std::endl;
std::cout << "Base<T>::member = " << Base<T>::member << std::endl;
}
};
int main()
{
Derived<int> derived;
std::cout << " --- Call baseMemberFunction --- " << std::endl;
derived.baseMemberFunction();
std::cout << " --- Call derivedMemberFunction --- " << std::endl;
derived.derivedMemberFunction();
return 0;
}
Related
I have a polymorphic NVI class to provide an adapter for Runtime-Polymorphism.
Type-erasure is used for loose coupling.
The non-owning implementation can be optimized out in a compile-time context:
// usage just for reference
printer referenced{"Referenced"};
const auto &polymorphicPrinter = polymorphic(referenced);
polymorphicPrinter.print(8.15);
// how to optimize this?
const auto &owningPolymorhic = polymorphic(std::make_unique<printer>("Owned");
However, I am not sure what is a simple or elegant way to allow passing the ownership and still have optimization like in the above case when it is possible.
Here is my naive implementation. I also added std::bad_function_call for invalid state.
// api_header.h
#pragma once
#include <memory>
#include <string_view>
#include <functional>
class polymorphic final
{
public:
template <typename T>
polymorphic(const T& t)
: pVTable_(getVTable(t)),
pObj_(std::addressof(t), [](const void*){})
{}
template <typename T>
polymorphic(std::unique_ptr<const T> t)
: pVTable_(getVTable(*t)),
pObj_(t.release(), [](const void* pObj){
delete static_cast<const T*>(pObj);
})
{}
template <typename T>
polymorphic(std::unique_ptr<T> t)
: polymorphic(std::unique_ptr<const T>(t.release()))
{}
polymorphic(const polymorphic&) = delete;
polymorphic& operator=(const polymorphic&) = delete;
polymorphic(polymorphic&& other) noexcept
: pVTable_(other.pVTable_),
pObj_(std::move(other.pObj_))
{
other.pVTable_ = polymorphic::getInvalidVTable();
}
polymorphic& operator=(polymorphic &&other) noexcept
{
pVTable_ = other.pVTable_;
pObj_ = std::move(other.pObj_);
other.pVTable_ = polymorphic::getInvalidVTable();
return *this;
}
template <typename T>
void print(T v) const
{
pVTable_->print(pObj_.get(), v);
}
private:
polymorphic() = default;
struct v_table {
virtual void print(const void *, double) const
{
throw std::bad_function_call();
}
virtual void print(const void *, std::string_view) const
{
throw std::bad_function_call();
}
protected:
~v_table() = default;
};
static const v_table *getInvalidVTable()
{
struct : v_table {} constexpr static invalidVTable{};
return &invalidVTable;
}
template <typename T>
static const v_table *getVTable(const T&)
{
struct : v_table {
void print(const void *pObj, double v) const override
{
static_cast<const T*>(pObj)->print(v);
}
void print(const void *pObj, std::string_view v) const override
{
static_cast<const T*>(pObj)->print(v);
}
} constexpr static vTable{};
return &vTable;
}
private:
const v_table *pVTable_ = getInvalidVTable();
// TODO: optimisation-friendly?
std::unique_ptr<const void, std::function<void(const void*)>> pObj_;
};
// main.cpp
#include "api_header.h"
#include <cstddef>
#include <string>
#include <iostream>
class printer
{
public:
template <size_t L>
explicit printer(const char (&name)[L])
: name_(name, L)
{}
void print(int v) const
{
std::cout << name_ << ": " << v << std::endl;
}
void print(double v) const
{
std::cout << name_ << ": " << v << std::endl;
}
void print(std::string_view v) const
{
std::cout << name_ << ": " << v << std::endl;
}
~printer()
{
std::cout << name_ << " destroyed\n";
}
private:
std::string name_;
};
int main()
{
printer pReferenced{"referenced"};
{
const auto &polyReferenced = polymorphic(pReferenced);
polyReferenced.print(4);
polyReferenced.print(8.15);
polyReferenced.print("oceanic");
std::cout << "non-owning polymorphic destroyed\n\n";
}
{
const auto &polyOwned = polymorphic(std::make_unique<printer>("owned"));
polyOwned.print(4);
polyOwned.print(8.15);
polyOwned.print("oceanic");
}
std::cout << "owning polymorphic destroyed\n\n";
std::cout << "Invalidating polymorphic reference\n";
try {
auto invalidReferenced = polymorphic(pReferenced);
auto polyMoved = std::move(invalidReferenced);
polyMoved.print("I have been moved");
invalidReferenced.print("This will throw");
}
catch (const std::bad_function_call &e)
{
std::cout << "error: " << e.what() << std::endl;
}
}
This code:
https://godbolt.org/z/Pc8981ns8
Is it possible to make this code optimization-friendly?
Please see the following code:
// templateClassTemplate.cpp
#include <iostream>
class Account{
public:
explicit Account(double amount=0.0): balance(amount){}
void deposit(double amount){
balance+= amount;
}
void withdraw(double amount){
balance-= amount;
}
double getBalance() const{
return balance;
}
private:
double balance;
};
template <typename T, int N>
class Array{
public:
Array()= default;
int getSize() const;
private:
T elem[N];
};
template <typename T, int N>
int Array<T,N>::getSize() const {
return N;
}
int main(){
std::cout << std::endl;
Array<double,10> doubleArray;
std::cout << "doubleArray.getSize(): " << doubleArray.getSize() << std::endl;
Array<Account,1000> accountArray;
std::cout << "accountArray.getSize(): " << accountArray.getSize() << std::endl;
std::cout << std::endl;
}
This code is taken from a learning course on template initialisation.
I have two questions:
How is the object Array<double,10> doubleArray initialized since it is using a default constructor that takes no arguments?
How is the object Array<Account,1000> accountArray initialized?
The template is instantiated by replacing the type T in the template with the type given as the first argument, and the integer N with the value of the second argument.
The same thing happens when instantiating the definition of getSize.
That is, Array<double,10> doubleArray; works exactly the same as
class DoubleArray10{
public:
DoubleArray10()= default;
int getSize() const;
private:
double elem[10];
};
int DoubleArray10::getSize() const { return 10; }
DoubleArray10 doubleArray;
and Array<Account,1000> accountArray; works exactly like
class AccountArray1000{
public:
AccountArray1000()= default;
int getSize() const;
private:
Account elem[1000];
};
int AccountArray1000::getSize() const { return 1000; }
AccountArray1000 accountArray;
I read this article about C++ factory class with a self registering capability of the concrete classes. Really like it, expecially the demangled name solution used as a key for the registered classes.
There is one main issue I would like to solve: how can we modify the factory to be able to support concrete classes with different constructor parameters?
// Dog and Cat both derive from Animal, but have different constructor parameters
class Dog : public Animal::Registrar<Dog> {
public:
Dog(int param1, std::string param2) : m_x(param1) {}
void makeNoise() { std::cerr << "Dog: " << m_x << "\n"; }
private:
int m_x;
};
class Cat : public Animal::Registrar<Cat> {
public:
Cat(bool param1) : m_flag(param1) {}
void makeNoise() { std::cerr << "Cat: " << m_x << "\n"; }
private:
bool m_flag;
};
I was thinking that maybe the parameter pack of template <class Base, class... Args> class Factory should be moved to the template <class T> struct Registrar, but I can't found a proper solution.
Full original code below
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <cstdlib>
#include <cxxabi.h>
std::string demangle(const char *name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
std::unique_ptr<char, void (*)(void *)> res{
abi::__cxa_demangle(name, NULL, NULL, &status), std::free};
return (status == 0) ? res.get() : name;
}
template <class Base, class... Args> class Factory {
public:
template <class ... T>
static std::unique_ptr<Base> make(const std::string &s, T&&... args) {
return data().at(s)(std::forward<T>(args)...);
}
template <class T> struct Registrar : Base {
friend T;
static bool registerT() {
const auto name = demangle(typeid(T).name());
Factory::data()[name] = [](Args... args) -> std::unique_ptr<Base> {
return std::make_unique<T>(std::forward<Args>(args)...);
};
return true;
}
static bool registered;
private:
Registrar() : Base(Key{}) { (void)registered; }
};
friend Base;
private:
class Key {
Key(){};
template <class T> friend struct Registrar;
};
using FuncType = std::unique_ptr<Base> (*)(Args...);
Factory() = default;
static auto &data() {
static std::unordered_map<std::string, FuncType> s;
return s;
}
};
template <class Base, class... Args>
template <class T>
bool Factory<Base, Args...>::Registrar<T>::registered =
Factory<Base, Args...>::Registrar<T>::registerT();
struct Animal : Factory<Animal, int> {
Animal(Key) {}
virtual void makeNoise() = 0;
};
class Dog : public Animal::Registrar<Dog> {
public:
Dog(int x) : m_x(x) {}
void makeNoise() { std::cerr << "Dog: " << m_x << "\n"; }
private:
int m_x;
};
class Cat : public Animal::Registrar<Cat> {
public:
Cat(int x) : m_x(x) {}
void makeNoise() { std::cerr << "Cat: " << m_x << "\n"; }
private:
int m_x;
};
// Won't compile because of the private CRTP constructor
// class Spider : public Animal::Registrar<Cat> {
// public:
// Spider(int x) : m_x(x) {}
// void makeNoise() { std::cerr << "Spider: " << m_x << "\n"; }
// private:
// int m_x;
// };
// Won't compile because of the pass key idiom
// class Zob : public Animal {
// public:
// Zob(int x) : Animal({}), m_x(x) {}
// void makeNoise() { std::cerr << "Zob: " << m_x << "\n"; }
// std::unique_ptr<Animal> clone() const { return
// std::make_unique<Zob>(*this); }
// private:
// int m_x;
// };
// An example that shows that rvalues are handled correctly, and
// that this all works with move only types
struct Creature : Factory<Creature, std::unique_ptr<int>> {
Creature(Key) {}
virtual void makeNoise() = 0;
};
class Ghost : public Creature::Registrar<Ghost> {
public:
Ghost(std::unique_ptr<int>&& x) : m_x(*x) {}
void makeNoise() { std::cerr << "Ghost: " << m_x << "\n"; }
private:
int m_x;
};
int main() {
auto x = Animal::make("Dog", 3);
auto y = Animal::make("Cat", 2);
x->makeNoise();
y->makeNoise();
auto z = Creature::make("Ghost", std::make_unique<int>(4));
z->makeNoise();
return 0;
}
I'm trying to override a virtual method based on the members signedness, but somehow I don't get it right.
I'm using Visual Studio 2010 which doesn't support full C++11 but also in gcc it doesn't compile.
#ifndef SIGNED_TEMPLATE_H_
#define SIGNED_TEMPLATE_H_
#include <type_traits>
#include <iostream>
class Base
{
public:
Base(void) {}
virtual ~Base(void) {}
virtual bool toValue(int *p) = 0;
void Signed(bool bSigned) { mSigned = bSigned; }
bool Signed(void) const { return mSigned; }
private:
bool mSigned;
};
template<typename T>
class ColumnDef : public Base
{
public:
ColumnDef(void) {}
template<typename T,
typename = std::enable_if<std::is_signed<T>::value>>
bool toValue(int *p) override
{
std::cout << "Signed" << std::endl;
return true;
}
template<typename T,
typename = std::enable_if<std::is_unsigned<T>::value>>
bool toValue(int *p) override
{
std::cout << "Unsigned" << std::endl;
return true;
}
};
#endif /* SIGNED_TEMPLATE_H_ */
Your override is wrong...
You have to forward your call, something like:
template<typename T>
class ColumnDef : public Base
{
public:
ColumnDef() {}
bool toValue(int *p) override
{
return toValueImpl(p, std::is_unsigned<T>{});
}
private:
bool toValueImpl(int *p, std::true_type)
{
std::cout << "Signed" << std::endl;
return true;
}
bool toValueImpl(int *p, std::false_type)
{
std::cout << "Unsigned" << std::endl;
return true;
}
};
You can't mix dynamic and static polymorphism, virtual functions can not be template.
The answer of Jarod42 is probably simpler, but just to demonstrate how you could use enable_if in this case:
class ColumnDef : public Base
{
public:
ColumnDef(void) {}
bool toValue(int *p)override
{
return toValueImpl<T>(p);
}
private:
template<typename T1>
typename std::enable_if<std::is_signed<T1>::value,bool>::type toValueImpl(int *p)
{
std::cout << "Signed" << std::endl;
return true;
}
template<typename T1>
typename std::enable_if<std::is_unsigned<T1>::value,bool>::type toValueImpl(int *p)
{
std::cout << "Unsigned" << std::endl;
return true;
}
};
I have written a small piece of code where I am able to call setter and getter functions packed within a functoid using mem_fun templates.
I now would like to use this approach on top of a class hierarchy where every class might have getter and setter which can be registered as pair within a vector or array to be able to call the getter and setter if needed. GUIObject and GUICompositeObject are example classes out of the described class hierarchy.
The bound_mem_fun_t for the objects have unfortunately different types and thats the reason I don't know how to integrate them into an array/vector of pointers to the functors.
In c++11 I would use std::function. Is there a way to emulate this in c++98?
Because our compiler support only c++98 I cannot use the new features of c++11 or c++14. Also boost is not allowed.
#include <functional>
class GUIObject
{
int m_Alpha;
public:
void SetAlpha(int a) { m_Alpha = a;};
int GetAlpha() {return m_Alpha;};
};
class GUICompositeObject: public GUIObject
{
int m_NumOfChilds;
public:
void SetNumOfChilds(int NumOfChilds) { m_NumOfChilds = NumOfChilds;};
int GetNumOfChilds() {return m_NumOfChilds;};
};
template<typename T>
struct bound_mem_fun_t
{
bound_mem_fun_t(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o) :
m_GetFunc(GetFunc), m_SetFunc(SetFunc), obj(o) { } ;
int operator()() { return m_GetFunc(obj); } ;
void operator()(int i) { m_SetFunc(obj, i); } ;
std::mem_fun_t<int, T> m_GetFunc;
std::mem_fun1_t<void, T, int> m_SetFunc;
T* obj;
};
int main()
{
GUIObject kGUIObject;
GUICompositeObject kCompObj;
bound_mem_fun_t<GUIObject> GUIObjectFunc(std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject);
GUIObjectFunc(17);
int ii = GUIObjectFunc();
bound_mem_fun_t<GUICompositeObject> GUICompObjectFunc(std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj);
GUICompObjectFunc(17);
int iChilds = GUICompObjectFunc();
return 0;
}
Here is the complete solution after #filmors answer:
#include <functional>
#include <vector>
#include <iostream>
class GUIObject
{
int m_Alpha;
public:
void SetAlpha(int a) { m_Alpha = a;};
int GetAlpha() {return m_Alpha;};
};
class GUICompositeObject: public GUIObject
{
int m_NumOfChilds;
public:
void SetNumOfChilds(int NumOfChilds) { m_NumOfChilds = NumOfChilds;};
int GetNumOfChilds() {return m_NumOfChilds;};
};
struct bound_mem_fun_base
{
virtual int operator()() =0;
virtual void operator()(int) =0;
};
template<typename T>
struct bound_mem_fun_t : public bound_mem_fun_base
{
bound_mem_fun_t(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o) :
m_GetFunc(GetFunc), m_SetFunc(SetFunc), obj(o) { } ;
virtual int operator()() { return m_GetFunc(obj); } ;
virtual void operator()(int i) { m_SetFunc(obj, i); } ;
std::mem_fun_t<int, T> m_GetFunc;
std::mem_fun1_t<void, T, int> m_SetFunc;
T* obj;
};
template<typename T> bound_mem_fun_t<T>* make_setter(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o)
{
return new bound_mem_fun_t<T> (GetFunc, SetFunc, o);
}
int main()
{
GUIObject kGUIObject;
GUICompositeObject kCompObj;
std::vector<bound_mem_fun_base*> kBoundVector;
kBoundVector.push_back(new bound_mem_fun_t<GUIObject> (std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject));
kBoundVector.push_back(new bound_mem_fun_t<GUICompositeObject> (std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj));
kBoundVector.push_back(make_setter<GUIObject> (std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject));
kBoundVector.push_back(make_setter<GUICompositeObject> (std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj));
for (int i = 0; i < 4 ; i++)
{
(*kBoundVector[i])(i*10);
int res = (*kBoundVector[i])();
std::cout << "Getter result " << res << "\n";
}
return 0;
}
Unfortunately the make_setter function does not really shorten the creation of the functor. Any ideas will be welcome.
Just give your bound_mem_fun_t<T> a common base class and use dynamic dispatch to solve your problem:
struct bound_mem_fun_base {
virtual int operator()() = 0;
virtual void operator()(int) = 0;
};
template <typename T>
struct bound_mem_fun_t : bound_mem_fun_t ...
Then you can keep pointers to bound_mem_fun_base in your vector and call the elements as (*v[0])().
Also, TR1 does contain std::tr1::function, is that available?
First a remark on std::function from c++11: That will not solve your problem, because you need an already bounded function pointer. This pointer must be bound to your object. I believe what you need is an own implementation to std::bind.
I started only a very! small Binder class which is hopefully a starting point for your needs. If you need to have template parameter lists in older c++ versions, take a look for loki. http://loki-lib.sourceforge.net/
As a hint I can give you a short example of what i did:
class A
{
private:
int val;
public:
A(int i): val(i) {}
void Do(int i) { std::cout << "A " << val<< " " << i << std::endl; }
};
class B
{
private:
int val;
public:
B(int i): val(i){}
void Go(int i) { std::cout << "B " << val << " " << i << std::endl; }
};
class Base
{
public:
virtual void operator()(int i)=0;
};
template <typename T>
class Binder: public Base
{
void (T::*fnct)(int);
T* obj;
public:
Binder( void(T::*_fnct)(int), T*_obj):fnct(_fnct),obj(_obj){}
void operator()(int i)
{
(obj->*fnct)(i);
}
};
int main()
{
A a(100);
B b(200);
// c++11 usage for this example
//std::function<void(int)> af= std::bind( &A::Do, &a, std::placeholders::_1);
//af(1);
// hand crafted solution
Base* actions[2];
actions[0]= new Binder<A>( &A::Do, &a);
actions[1]= new Binder<B>( &B::Go, &b);
actions[0]->operator()(55);
actions[1]->operator()(77);
}