Change Operation at runtime in C++ - c++

I have a small problem at hand. Suppose there is a if condition with only 2 operands but I want to make the operation dynamic.
void somFunc()
{
if(a && b) /*1*/
{
}
else if(a1 && b1) /*2*/
{
}
else if(a || b) /*3*/
{
}
else if(a1 || b1) /*4*/
}
Basically, 1 and 3 exactly has same parameters with different operation,Similarly for 2 and 4. I want to reduce these 4 operations to 2.
I want to know if there is a way I can make oper dynamic. Consider we only have 2 operations && and ||Can I use templates in any way ?
If someone wants to know why I need this is, there are n if conditions inside a big if/else. If I somehow achieve this, I reduce the conditions by half.

Not sure if this is what you are asking for, but you can write something like this:
enum OPERATION { AND, OR };
bool operation(bool a, bool b,OPERATION op) {
if (op == AND) return a && b;
return a || b;
}
void somFunc(OPERATION op)
{
if(operation(a,b,op))
{
}
}
Or as suggested in a comment, make the operation to be performed a parameter of the function, like so
template <OPERATION>
void somFunc(OPERATION op)
{
if(op(a,b))
{
}
}
and call it like this
somFunc( [](bool a, bool b) { return a && b; });
somFunc( [](bool a, bool b) { return a || b; });

You can use pointers to funtions.
#include <iostream>
#include <functional>
bool oper1(bool a, bool b) {
return a || b;
}
bool oper2(bool a, bool b) {
return a && b;
}
int main() {
bool a = true, b = false;
auto oper = oper1;
if (oper(a, b)) {
std::cout << "OR\n";
}
oper = oper2;
if (oper(a, b)) {
std::cout << "AND\n";
}
}
First you define all your conditions and later you can switch the condition by setting the variable.
You can also use inheritance and functors:
#include <iostream>
#include <functional>
#include <memory>
class Operator {
public:
virtual bool eval(bool a, bool b) = 0;
};
class OrOperator : public Operator {
public:
bool eval(bool a, bool b) {
return a || b;
}
};
class AndOperator : public Operator {
public:
bool eval(bool a, bool b) {
return a && b;
}
};
class VariableOperator : public Operator {
public:
VariableOperator(bool val) : val(val) {}
bool eval(bool a, bool b) {
return val;
}
private:
bool val;
};
int main() {
bool a = true, b = false;
std::unique_ptr<Operator> oper(new OrOperator);
if (oper->eval(a, b)) {
std::cout << "OR\n";
}
oper.reset(new AndOperator);
if (oper->eval(a, b)) {
std::cout << "AND\n";
}
oper.reset(new VariableOperator(true));
if (oper->eval(a, b)) {
std::cout << "VARIABLE\n";
}
}

You might be looking for something like this:
void somFunc()
{
std::vector< std::function< bool(bool, bool) > > operators = {
[](bool a, bool b){ return a && b; },
[](bool a, bool b){ return a || b; }
};
for ( auto& op : operators )
{
if ( op( a, b ) )
{
}
else if ( op( a1, b1 ) )
{
}
}
}
You can add more operators or change the parameter types easily enough.

You can do this with CRTP too:
#include <iostream>
#include <string>
#include <memory>
template<class T>
class Operation
{
public:
bool eval(bool a, bool b)
{
return this->impl().eval(a,b);
}
private:
T& impl() { return static_cast<T&>(*this); }
};
class AndOperation : public Operation<AndOperation>
{
public:
bool eval(bool a, bool b)
{
return a && b;
}
};
class OrOperation : public Operation<OrOperation>
{
public:
bool eval(bool a, bool b)
{
return a || b;
}
};
int main()
{
AndOperation andOp;
auto anonOp = std::make_unique<OrOperation>();
std::cout << andOp.eval(true, true) << std::endl;
std::cout << anonOp->eval(false,false);
}
see live example here
What are the advantages of CRTP over virtual inheritance?
CRTP is a case of static polymorphism. Here's some references:
Compile time vs run time polymorphism in C++ advantages/disadvantages
What is the motivation behind static polymorphism in C++?
C++: How is this technique of compile-time polymorphism called and what are the pros and cons?
The cost of dynamic (virtual calls) vs. static (CRTP) dispatch in C++

It is possible to make somFunc() a template, and accept any function that accepts two arguments and returns a value that can be tested with if.
#include <functional> // for binary operations in std
template<class Operation> void somfunc(Operation oper)
{
if (oper(a,b))
{
// whatever
}
}
int main()
{
somFunc(std::logical_and<int>());
somFunc(std::logical_or<int>());
somFunc(std::plus<int>()); // addition
// pass a lambda
somFunc([](int a, int b) -> int {return a + b;}); // lambda form of addition
}
In the above, I've assumed the variables a and b (which have been used in the question, but types unspecified) are of type int.

Related

How can I pass a class method as a parameter to another function and later call it, preferably making the variable class method signature explicit?

If I have a class that needs to call a parent class method with a class method as parameter I can do it with std::function + std::bind as shown below:
class A {
void complexMethod(std::function<void()> variableMethod) {
// other stuff ...
variableMethod();
// some other stuff..
}
}
class B : public A {
void myWay() {
// this and that
}
void otherWay() {
// other and different
}
void doingSomething() {
// Preparing to do something complex.
complexMethod(std::bind(&B::myWay, this));
}
void doingAnotherThing() {
// Different preparation to do some other complex thing.
complexMethod(std::bind(&B::otherWay, this));
}
}
How would I need to change the above code to implement the same thing using templates instead of std::function + std::bind?
And how about lambdas instead of std::function + std::bind? I still want to call B:myWay() and B::otherWay() but using lambdas. I don't want to substitute B:myWay() and B::otherWay() with lambdas.
Is there any implementation technique (one of the above or some other) were I would be able to make variableMethod return type and parameters explicit? How would I do it? Let's say the signature of variableMethod is:
bool variableMethod(int a, double b);
Which technique is recommended? Why (speed, flexibility, readility...)?
Template + lambda solution:
struct A
{
template <typename F>
void runA(F func)
{
cout << 1 << endl;
func();
cout << 3 << endl;
}
};
struct B : A
{
int number = 2;
void runnable() { cout << number << endl; }
void runB()
{
cout << 0 << endl;
runA([this]() { runnable(); });
cout << 4 << endl;
}
};
int main()
{
B variable;
variable.runB();
}
In order to take a function as template parameter, just take in a template type of that function like above. lambdas can be used instead of bind to make things easier (this is passed to lambda captures list).
Explicitly declaring the arguments:
void run_func(std::function<bool(int, double)> func)
{
bool b = func(10, 10.01);
}
std::function allows you to define your arguement and return types like above.
How would I need to change the above code to implement the same thing
using templates instead of std::function + std::bind?
And how about lambdas instead of std::function + std::bind? I
still want to call B:myWay() and B::otherWay() but using lambdas.
I don't want to substitute B:myWay() and B::otherWay() with
lambdas.
You can use a lambda, yes.
Something like [this]() { return myWay(); } that:
captures this, and
calls a method of the current object.
[Demo]
#include <iostream> // cout
class A {
protected:
template <typename F>
void complexMethod(F&& f) { f(); }
};
class B : public A {
void myWay() { std::cout << "myWay\n"; }
void otherWay() { std::cout << "otherWay\n"; }
public:
void doingSomething() {
complexMethod([this]() { return myWay(); });
}
void doingAnotherThing() {
complexMethod([this]() { return otherWay(); });
}
};
int main() {
B b{};
b.doingSomething();
b.doingAnotherThing();
}
// Outputs:
//
// myWay
// otherWay
Is there any implementation technique (one of the above or some other)
were I would be able to make variableMethod return type and
parameters explicit? How would I do it?
You could use const std::function<bool(int,double)>& f as the parameter receiving a function for complexMethod. And still pass a lambda. Notice though lambdas are now receiving (int i, double d) (it could be (auto i, auto d) as well).
[Demo]
#include <functional> // function
#include <ios> // boolalpha
#include <iostream> // cout
class A {
protected:
bool complexMethod(const std::function<bool(int,double)>& f, int i, double d)
{ return f(i, d); }
};
class B : public A {
bool myWay(int a, double b) { return a < static_cast<int>(b); }
bool otherWay(int a, double b) { return a*a < static_cast<int>(b); }
public:
bool doingSomething(int a, double b) {
return complexMethod([this](int i, double d) {
return myWay(i, d); }, a, b);
}
bool doingAnotherThing(int a, double b) {
return complexMethod([this](auto i, auto d) {
return otherWay(i, d); }, a, b);
}
};
int main() {
B b{};
std::cout << std::boolalpha << b.doingSomething(3, 5.5) << "\n";
std::cout << std::boolalpha << b.doingAnotherThing(3, 5.5) << "\n";
}
// Outputs:
//
// true
// false
Notice also the same could be accomplished with templates, although you wouldn't be making the signature explicit.
[Demo]
#include <functional> // function
#include <ios> // boolalpha
#include <iostream> // cout
class A {
protected:
template <typename F, typename... Args>
auto complexMethod(F&& f, Args&&... args) -> decltype(f(args...))
{ return f(args...); }
};
class B : public A {
bool myWay(int a, double b) { return a < static_cast<int>(b); }
bool otherWay(int a, double b) { return a*a < static_cast<int>(b); }
public:
bool doingSomething(int a, double b) {
return complexMethod([this](auto i, auto d) {
return myWay(i, d); }, a, b);
}
bool doingAnotherThing(int a, double b) {
return complexMethod([this](auto i, auto d) {
return otherWay(i, d); }, a, b);
}
};
int main() {
B b{};
std::cout << std::boolalpha << b.doingSomething(3, 5.5) << "\n";
std::cout << std::boolalpha << b.doingAnotherThing(3, 5.5) << "\n";
}
// Outputs:
//
// true
// false
Which technique is recommended? Why (speed, flexibility,
readility...)?
Item 34 of Scott Meyer's Effective Modern C++ book is titled Prefer lambdas to std::bind. It ends with a summary saying: Lambdas are more readable, more expressive, and may be more efficient than using std::bind. However, it also mentions a case when std::bind may be useful over lambdas.

c++ how to call function with subclass, having superclass pointer

I have 3 classes, A, B and C:
class A {
public:
virtual bool sm(B b) = 0;
virtual bool sm(C c) = 0;
};
class B : public A {
bool sm(B b) {
//code
}
bool sm(C c) {
//code
}
};
class C : public A {
bool sm(B b) {
//code
}
bool sm(C c) {
//code
}
};
And vector<A*> objects, that stores B or C objects. (for example they generates randomly)
Can I call somehow
for(int i = 0; i < objects.size(); i++) {
for(int j = i; j < objects.size(); j++) {
objects[i].sm(objects[j]);
}
}
Without dynamic cast or something? Because there can be a bit more of B-C classes
And is it a bag thing, and may be there is a better way to do it?
SOLUTION
As odelande said and I understood, this is the solution for my problem
#include <iostream>
#include <vector>
class B;
class C;
class A {
public:
virtual bool sm(A* a) = 0;
virtual bool sm(B* b) = 0;
virtual bool sm(C* c) = 0;
};
class B : public A {
public:
bool sm(A* a) {
return a->sm(this);
}
bool sm(B* b) {
std::cout << "In B doing B" << std::endl;
return true;
}
bool sm(C* c) {
std::cout << "In B doing C" << std::endl;
return false;
}
};
class C : public A {
public:
bool sm(A* a) {
return a->sm(this);
}
bool sm(B* b) {
std::cout << "In C doing B" << std::endl;
return true;
}
bool sm(C* c) {
std::cout << "In C doing C" << std::endl;
return false;
}
};
int main() {
std::vector<A*> objects;
objects.push_back(new B());
objects.push_back(new C());
objects[0]->sm(objects[0]);
objects[0]->sm(objects[1]);
objects[1]->sm(objects[0]);
objects[1]->sm(objects[1]);
std::cin.get();
return 0;
}
This code outputs
In B doing B
In C doing B
In B doing C
In C doing C
You cannot do it like this. The overloads of the sm() method are statically resolved, i.e. at compile time (besides, sm() should take pointers to B and C). But the compiler only knows that objects[j] is an A*; it cannot resolve the call because there is no overload that takes a A* as input.
What you want is to dispatch the call based on the runtime type of objects[j]. This is what a call to a virtual function does. So, you should only have one sm() method, which should in turn call another virtual method of its argument.
You're searching for the Visitor Pattern, multiple dispatch. The key is that you take a reference in sm(A& a) and call smT(...) on it. (Code is for example purposes only, will need clean-up and consts.)
class A {
protected:
virtual bool smB(B& b) = 0;
virtual bool smC(C& c) = 0;
public:
virtual bool sm(A& a) = 0;
};
class B : public A {
protected:
bool smB(B& b) {
// code,
}
bool smC(C& b) {
// code
}
public:
bool sm(A& a) {
a.smB( *this ); // this is smC(...) in class C
}
};

What is this operator overloading function overloading?

I am looking through the CMBC source code and came across this code snippet:
void goto_symext::operator()(const goto_functionst &goto_functions)
{
goto_functionst::function_mapt::const_iterator it=
goto_functions.function_map.find(goto_functionst::entry_point());
if(it==goto_functions.function_map.end())
throw "the program has no entry point";
const goto_programt &body=it->second.body;
operator()(goto_functions, body);
}
I have never seen a operator()(args) syntax before and googling does not seem to yield anything.
As answered in the comments, /*return type*/ operator()(/*params*/) is the syntax for overloading the () operator.
struct Foo { void operator()() { std::cout << "Hello, world!"; } };
Foo f;
f(); //Hello, world!
That would be the function call operator, which allows you to make function-like objects.
struct Functor {
bool operator()(int a, int b = 3);
};
bool Functor::operator()(int a, int b /* = 3 */) {
if ((a > (2 * b)) || (b > (2 * a))) {
return true;
} else {
return false;
}
}
// ...
Functor f;
bool b = f(5); // Calls f.operator()(5, 3).
bool c = f(3, 5);
It has the benefits that you can save state information in the function-like object's fields, and that if necessary, you can hide overloaded versions of the operator within the object instead of leaving them exposed.
class Functor {
int compareTo;
public:
Functor(int cT);
bool operator()(int a);
bool operator()(char c);
};
Functor::Functor(int cT) : compareTo(cT) { }
bool Functor::operator()(int a) {
if ((a > (2 * compareTo)) || (compareTo > (2 * a))) {
return true;
} else {
return false;
}
}
bool Functor::operator()(char c) { return false; }
It can be used to make it easier to write code that can accept any function instead of depending on function pointers. [It works especially well when used in tandem with templates, in this regard.]
See here or here for more information.

one to one association

What is the best way to represent one-to-one object association in C++? It should be as automatic and transparent as possible meaning, that when one end is set or reset, the other end will be updated. Probably a pointer-like interface would be ideal:
template<typename AssociatedType>
class OneToOne{
void Associate(AssociatedType &);
AssociatedType &operator* ();
AssociatedType *operator->();
}
Is there any better way to do it or is there any complete implementation?
EDIT:
Desired behavior:
struct A{
void Associate(struct B &);
B &GetAssociated();
};
struct B{
void Associate(A &);
A &GetAssociated();
};
A a, a2;
B b;
a.Associate(b);
// now b.GetAssociated() should return reference to a
b.Associate(a2);
// now b.GetAssociated() should return reference to a2 and
// a2.GetAssociated() should return reference to b
// a.GetAssociated() should signal an error
Untested, but you could use a simple decorator
template <typename A1, typename A2>
class Association
{
public:
void associate(A2& ref)
{
if (_ref && &(*_ref) == &ref) return; // no need to do anything
// update the references
if (_ref) _ref->reset_association();
// save this side
_ref = ref;
ref.associate(static_cast<A1&>(*this));
}
void reset_association() { _ref = boost::none_t(); }
boost::optional<A2&> get_association() { return _ref; }
private:
boost::optional<A2&> _ref;
};
now:
struct B;
struct A : public Association<A, B> {
};
struct B : public Association<B, A> {
};
now these operations should be handled correctly.
A a, a2;
B b;
a.associate(b);
b.associate(a2);
NOTES: I use boost::optional to hold a reference rather than pointer, there is nothing stopping you from using pointers directly. The construct you are after I don't think exists by default in C++, which is why you need something like the above to get it to work...
Here is one class that can represent a bi-directional one-to-one relation:
template <class A, class B>
class OneToOne {
OneToOne<A,B>* a;
OneToOne<A,B>* b;
protected:
OneToOne(A* self) : a(self), b(0) {}
OneToOne(B* self) : a(0), b(self) {}
public:
void associateWith(OneToOne<A,B>& other) {
breakAssociation();
other.breakAssociation();
if (a == this) {
if (b != &other) {
breakAssociation();
other.associateWith(*this);
b = &other;
}
}
else if (b == this) {
if (a != &other) {
breakAssociation();
other.associateWith(*this);
a = &other;
}
}
}
A* getAssociatedObject(B* self) { return static_cast<A*>(a); }
B* getAssociatedObject(A* self) { return static_cast<B*>(b); }
void breakAssociation() {
if (a == this) {
if (b != 0) {
OneToOne<A,B>* temp = b;
b = 0;
temp->breakAssociation();
}
}
else if (b == this) {
if (a != 0) {
OneToOne<A,B>* temp = a;
a = 0;
temp->breakAssociation();
}
}
}
private:
OneToOne(const OneToOne&); // =delete;
OneToOne& operator=(const OneToOne&); // =delete;
};
Perhaps check out boost::bimap, a bidirectional maps library for C++.

operator as template parameter

Is it possible?
template<operator Op> int Calc(int a, b)
{ return a Op b; }
int main()
{ cout << Calc<+>(5,3); }
If not, is way to achieve this without ifs and switches?
You could use functors for this:
template<typename Op> int Calc(int a, int b)
{
Op o;
return o(a, b);
}
Calc<std::plus<int>>(5, 3);
No - templates are about types or primitive values.
You can nontheless pass so called function objects that can be called like functions and carry the desired operator functionality (despite having a nice syntax).
The standard library defines several ones, e.g. std::plus for addition ...
#include <functional>
template<typename Op>
int Calc(int a, int b, Op f) {
return f(a, b);
}
int main() {
cout << Calc(5,3, std::plus());
cout << Calc(5,3, std::minus());
}
You can do this using polymorphism:
#include <cstdlib>
#include <iostream>
using namespace std;
class Operator
{
public:
virtual int operator()(int a, int b) const = 0;
};
class Add : public Operator
{
public:
int operator()(int a, int b) const
{
return a+b;
}
};
class Sub : public Operator
{
public:
int operator()(int a, int b) const
{
return a-b;
}
};
class Mul : public Operator
{
public:
int operator()(int a, int b) const
{
return a*b;
}
};
int main()
{
Add adder;
cout << adder(1,2) << endl;
Sub suber;
cout << suber(1,2) << endl;
Mul muler;
cout << muler(1,2) << endl;
return 0;
}
If you refer to global operators, you have already received some answers. In some particular cases, though, it might also be helpful to use overloaded operator functions.
This might be trivial; nevertheless it might be helpful in some cases which is why I post one example:
#include <iostream>
template<typename opType, typename T>
int operation(opType op, T a, T b)
{
return (a.*op)(1) + (b.*op)(1);
}
struct linear
{
int operator()(int n) const {return n;}
int operator[](int n) const {return n * 10;}
};
int main()
{
linear a, b;
std::cout << operation(&linear::operator(), a, b) << std::endl
<< operation(&linear::operator[], a, b);
return 0;
}
output:
2
20
Use
template<typename Op>
int Calc(int a, int b, Op f) {
return f(a, b);
}
int
main() {
cout << Calc(5, 3, std::plus{});
cout << Calc(5, 3, std::minus{});
}
if Dario answer fails with error: cannot deduce template arguments for ‘plus’ from ()