Binding operator new? - c++

I'd like to bind operator new (see example below). If the constructor doesn't have any arguments, it works fine, but if it does have arguments, I apparently have trouble getting the bind syntax correct.
#include <map>
#include <boost\function.hpp>
#include <boost\lambda\lambda.hpp>
#include <boost\lambda\construct.hpp>
#include <boost\lambda\bind.hpp>
enum TypeEnum
{
BarType,
BazType
};
class Foo
{
};
class Bar : public Foo
{
public:
Bar(int x)
{ BarVal = x; }
private:
int barVal;
};
class Baz : public Foo
{
public:
Baz(int x)
{ bazVal = 2 * x; }
private:
int bazVal;
};
class FooFactory
{
public:
FooFactory()
{
// How does this work?
factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(_1));
factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(_1));
}
Foo* getFoo(TypeEnum type, int z)
{
return factoryMap[type](z);
}
private:
std::map<TypeEnum, boost::function<Foo* (int)>> factoryMap;
};
int main()
{
FooFactory fooFactory;
Bar *newBar = static_cast<Bar*> (fooFactory.getFoo(BarType, 10));
return 0;
}

This should do:
factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(), boost::lambda::_1);
factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(), boost::lambda::_1);

Why not just to write the following? I can't see any reason to use bind in your case.
factoryMap[BarType] = boost::lambda::new_ptr<Bar>();
factoryMap[BazType] = boost::lambda::new_ptr<Baz>();

Related

How the base class calls the closure passed by the derived class in c++?

I have a base class, and it have a member function that sometime will be called. Usually, this function have a parameter that pointing to itself.
class Base {
public:
std::function<bool(Base *, int)> foo;
private:
int x{};
public:
static std::shared_ptr<Base> create() {
return std::make_shared<Base>();
}
Base() = default;
const std::function<bool(Base *, int)> &getFoo() const {
return foo;
}
void setFoo(const std::function<bool(Base *, int)> &foo) {
Base::foo = foo;
}
int getX() const {
return x;
}
void setX(int x) {
Base::x = x;
}
};
But when I have a derived class, how can I set this member function? Although the base class pointer can point to a subclass object, but I directly passed into the derived object, the compiler does not pass.
class Derived : public Base {
public:
static std::shared_ptr<Derived> create() {
return std::make_shared<Derived>();
}
};
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Derived *derived, int x) -> bool { return derived->getX() > x; });
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}
error: no viable conversion from '(lambda at
main.cpp:62:15)' to 'const
std::function'
b->setFoo([](Derived *derived, int x) -> bool { return derived->getX() > x; });
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So, is there any good idea to pass a closure to base class, and base class call it instead of derived class, and the most important thing is that closure have a parameter which is point to who pass the closure!
Note
I am going to assume that for some reason the closure in question needs access to Derived's methods/data members, and the OP's example does not convey that very well. Otherwise, why not just use Base * as the input parameter:
b->setFoo([](Base *derived, int x) -> bool { return derived->getX() > x; });
#user3655463's answer contains the full code for this case.
Simple solution
In case the CRTP solution proposed by #Yuki does not work for you, you could just use Base * as an argument of the closure and static_cast it in the closure body (the compiler can optimize away the cast), like this:
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Base *derived, int x) -> bool {
return static_cast<Derived *>(derived)->getX() > x;
});
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}
Live example.
If you really need the type in the closure to be Derived *
In case having Base * in the closure is not acceptable, you could hide the setFoo method from Base with a special implementation in Derived which will do the cast for you:
class Derived : public Base {
public:
static std::shared_ptr<Derived> create() {
return std::make_shared<Derived>();
}
template <typename Closure>
void setFoo(Closure foo) {
Base::setFoo([foo](Base *base, int x) {
return foo(static_cast<Derived *>(base), x);
});
}
};
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Derived *derived, int x) -> bool {
return derived->getX() > x;
});
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}
This allows you to use the same interface as you have in your original main funciton.
Live example.
If you have a lot of derived classes, and don't want to hide that method over and over again in each class
Now things get a bit complicated, and note that it's a good chance doing something like this would be overengineering in your case, but I just want to demonstrate that it can be done - here is where CRTP comes into play. It is used to implement a mixin which provides an implementation of the setFoo method:
template <typename ConcreteDerived, typename DirectBase>
class EnableSetFooAndInherit : public DirectBase {
public:
template <typename Closure>
void setFoo(Closure foo) {
DirectBase::setFoo([foo](DirectBase *base, int x) {
return foo(static_cast<ConcreteDerived *>(base), x);
});
}
};
class Derived : public EnableSetFooAndInherit<Derived, Base> {
public:
static std::shared_ptr<Derived> create() {
return std::make_shared<Derived>();
}
};
class Derived2 : public EnableSetFooAndInherit<Derived2, Base> {
public:
static std::shared_ptr<Derived2> create() {
return std::make_shared<Derived2>();
}
};
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Derived *derived, int x) -> bool {
return derived->getX() > x;
});
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
auto d2 = Derived2::create();
d2->setX(77);
d2->setFoo([](Derived2 *derived, int x) -> bool {
return derived->getX() < x;
});
if (d2->getFoo()) {
auto res = d2->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}
Live example.
If a template base solution fits your style then this might work.
template <typename D>
class Base {
public:
std::function<bool(D*, int)> foo;
private:
int x{};
public:
static std::shared_ptr<Base> create() { return std::make_shared<Base>(); }
Base() = default;
const std::function<bool(D*, int)>& getFoo() const { return foo; }
void setFoo(const std::function<bool(D*, int)>& foo) { Base::foo = foo; }
int getX() const { return x; }
void setX(int x) { Base::x = x; }
};
class Derived : public Base<Derived> {
public:
static std::shared_ptr<Derived> create() { return std::make_shared<Derived>(); }
};
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Derived* derived, int x) -> bool { return derived->getX() > x; });
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}
Can't you just use Base (just as you designed):
d->setFoo([](Base* derived, int x) -> bool { return derived->getX() > x; });
Whole code:
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
#include <memory>
class Base {
public:
std::function<bool(Base *, int)> foo;
private:
int x{};
public:
static std::shared_ptr<Base> create() {
return std::make_shared<Base>();
}
Base() = default;
const std::function<bool(Base *, int)> &getFoo() const {
return foo;
}
void setFoo(const std::function<bool(Base *, int)> &foo) {
Base::foo = foo;
}
int getX() const {
return x;
}
void setX(int x) {
Base::x = x;
}
};
class Derived : public Base {
public:
static std::shared_ptr<Derived> create() {
return std::make_shared<Derived>();
}
};
int main() {
auto d = Derived::create();
d->setX(77);
d->setFoo([](Base* derived, int x) -> bool { return derived->getX() > x; });
if (d->getFoo()) {
auto res = d->foo(d.get(), 99);
std::cout << res << std::endl;
}
return 0;
}

Explicit cast from int to a user defined class, c++

How can I enable explicit casting from, lets say int, to a user defined class Foo?
I made a conversion constructor from int to Foo, but is that it? I could overload a cast operator from Foo to int, but that is not what I'm looking for.
Is there a way to enable this piece of code?
int i = 5;
Foo foo = (Foo)i;
Something like this:
struct Foo {
explicit Foo(int x) : s(x) { }
int s;
};
int main() {
int i = 5;
Foo foo =(Foo)i;
}
Read about converting constructor.
If you won't set constructor as explicit, it allows you to convert type (which constuctor accepts) to a (newly constructed) class instance.
Here is the example
#include <iostream>
template<typename T>
class Foo
{
private:
T m_t;
public:
Foo(T t) : m_t(t) {}
};
int main()
{
int i = 0;
Foo<int> intFoo = i;
double d = 0.0;
Foo<double> doubleFoo = d;
}
You need a constructor which accecpts an int
class Foo {
public:
Foo (int pInt) {
....
}
Foo (double pDouble) {
....
}
int i = 5;
Foo foo(i); // explicit constructors
Foo foo2(27);
Foo foo3(2.9);
Foo foo4 = i; // implicit constructors
Foo foo5 = 27;
Foo foo6 = 2.1;

Using an interface class as member type in another class

I'm trying to design a piece of code that entails the use of an algorithm. The algorithm should be easily replaceable by someone else in the future. So in my LargeClass there has to be a way to invoke a specific algorithm.
I provided some example code below. My idea was to make an interface class IAlgorithm so that you have to provide an implementation yourself. I thought you could initialize it to which ever derived class you wanted in the constructor of the LargeClass. However the below code doesn't compile in VS2015 because IAlgorithm: cannot instantiate abstract class
My question: How should I design this in order to get the result I want?
Thanks in advance!
Algorithm.h
class IAlgorithm
{
protected:
virtual int Algorithm(int, int) = 0;
};
class algo1 : public IAlgorithm
{
public:
virtual int Algorithm(int, int);
};
class algo2 : public IAlgorithm
{
public:
virtual int Algorithm(int, int);
};
Algorithm.cpp
#include "Algorithm.h"
int algo1::Algorithm(const int a, const int b)
{
// Do something
}
int algo2::Algorithm(const int a, const int b)
{
// Do something
}
Source.cpp
#include "Algorithm.h"
class LargeClass
{
private:
IAlgorithm algo;
};
int main()
{
}
My first thoughts on this would be, why use such a primitive interface?
OK, we have a requirement that some process needs an algorithm sent into it. This algorithm must be polymorphic, it must take two ints and return an int.
All well and good. There is already a construct for this in the standard library. It's call a std::function. This is a wrapper around any function object with a compatible interface.
example:
#include <functional>
#include <iostream>
class LargeClass
{
public:
using algorithm_type = std::function<int(int,int)>;
LargeClass(algorithm_type algo)
: _algo(std::move(algo))
{}
int apply(int x, int y) {
return _algo(x,y);
}
private:
algorithm_type _algo;
};
int test(LargeClass&& lc) {
return lc.apply(5,5);
}
int divide(int x, int y) { return x / y; }
int main()
{
// use a lambda
std::cout << test(LargeClass{ [](auto x,auto y){ return x + y; } });
// use a function object
std::cout << test(LargeClass{ std::plus<>() } );
// use a free function
std::cout << test(LargeClass{ divide } );
// use a function object
struct foo_type {
int operator()(int x, int y) const {
return x * 2 + y;
}
} foo;
std::cout << test(LargeClass{ foo_type() } );
std::cout << test(LargeClass{ foo } );
}

Dereferencing pointer to functor inside a dereferenced class

I have a functor like this
struct foo
{
int a;
foo(a) : a(a) {}
int operator()(int b) { return a+b; }
};
And a class like this
class bar
{
public:
foo* my_ftor;
bar(foo* my_ftor) : my_ftor(my_ftor) {}
~bar() {}
};
Then suppose a pointer to this class, which contains a pointer to foo.
foo MyFoo(20);
bar MyBar(&MyFoo);
In a function I pass a reference to bar, and I want to run the functor. I got it working the following way:
void AnyFunction(bar* RefToBar)
{
int y;
y = RefToBar->my_ftor->operator()(25);
}
Is there any other "cleaner" way to dereference the functor? Something akin to
y = RefToBar->my_ftor(25);
won't work, sadly...
Any idea? Thank you
Use real references:
class bar {
public:
foo &my_ftor;
bar (foo &f) : my_ftor(f) {}
};
void AnyFunction (bar &reftobar) {
int y = reftobar.my_ftor(25);
}
And call like this
foo myFoo(20);
bar myBar (myFoo);
AnyFunction (myBar);
In the interest of completeness, here is another answer that is more of a modern approach.
class foo {
public:
foo (int i) : a(i) {}
int operator() (int x) const {
return x + a;
}
private:
int a;
};
template <typename F>
void AnyFunction (const F &func) {
int y = func(25);
}
So you can pass in a foo directly:
AnyFunction (foo (20));
Or another kind of function object, like a lambda:
AnyFunction([](int x) -> int {
return x + 20;
});
You could also extend bar to include the following function:
int run_foo (int x) const {
return my_ftor (x);
}
And bind it (#include <functional>):
AnyFunction (std::bind (&bar::run_foo, &myBar, std::placeholders::_1));
Use std::function they are designed to hold functor of any sort.
#include <functional>
#include <iostream>
struct foo
{
int _a;
foo(int a) : _a(a) {}
int operator()(int b) { return _a+b; }
};
class bar
{
public:
std::function<int (int)> _ftor;
bar(std::function<int (int)> my_ftor) : _ftor(my_ftor) {}
~bar() {}
};
void AnyFunction(bar& RefToBar)
{
int y = RefToBar._ftor(25);
std::cout << "Y: " << y << std::endl;
}
int AnotherFunction(int b)
{
return b + 11;
}
int main(int argc, char const *argv[])
{
foo MyFoo(20);
bar MyBar(MyFoo);
bar MyBar_2(AnotherFunction);
bar MyBar_3([](int b) { return b + 56; });
AnyFunction(MyBar);
AnyFunction(MyBar_2);
AnyFunction(MyBar_3);
return 0;
}
http://ideone.com/K3QRRV
y = (*RefToBar->my_ftor)(25);
(better use std::function and don't violate demeter)

fail to use type in public method

namespace iris {
namespace imon {
class myclass {
private:
typedef enum ppTag {
X1 = 0,
X2 = 1,
X3 = 254,
X4 = 255
} pp;
typedef struct {
int x;
int y;
int z;
} Data;
pp myFunc();
public:
myclass() { };
virtual ~myclass() {};
int func();
};
pp myclass::myFunc()
{
...
}
int myclass::func()
{
return 0;
}
}
}
g++ returns error: pp does not name a type
I thought I can easily use privately declared structures, typedefs etc. within public methods of the class. What else am I doing wrong?
You need to qualify the type in order to access it:
myclass::pp myclass::myFunc()
{
...
}