Would that be possible to help me to pass a functor, such as :
struct BFunc
{
double operator()(const double x, const double y, const double z){
return 0.1;
}
};
to a the constructor of a class:
class foo
{
int n;
public:
foo();
foo(int nn, &bfunc):n(nn),f(func()){
}
double getResult(double x){
return f(x);
}
}
Thanks,
Thank you all for your quick response. I solved it, by declaring a variable of type functor as bellow. But I was wondering if it is possible to do it without that. The point is I wanted to create a class, which I pass a function as boundary condition and a range to it, so it creates a 2D or 3D matrix of coordinates which gives zero to all points inside and zero to all points outside. I wanted to make it as general as possible. Eventually I ended up to follow following method.
using namespace std;
struct functor {
int a=11;
int operator () (int x) const {
cout << a << endl;
return 2*x;
}
};
class myclass {
int y=0;
functor af;// ** I did not wanted to have this line and make it generic ** //
public:
template <typename F> myclass(const F & f):af(f){
//af=f;//auto af(f);
y=f(5);
cout<<"y is"<<y<<endl;
int z=af(5);
cout<<"z is"<<z<<endl;
cout<<" why "<<typeid(af).name()<<endl;
}
int getFuncX(int x){
int y=af(x);
return y;
}
};
int main(int argc, char **argv) {
functor f = {5};
myclass c(f);
cout<<" See What happens: "<<c.getFuncX(71)<<endl;
return 0;
}
Sorry if it is messy! As you guessed I am a beginner.
Thanks
Related
I'm trying to make this code work:
#include <iostream>
using namespace std;
int f(int x) {
return x+1;
}
class A {
public:
int g(int y);
};
int A::g(int y) = f;
int main() {
A test;
cout << test.g(3) << endl;
return 0;
}
It does not compile because of the line int A::g(int y) = f;.
What is the correct way to achieve that an external function can be used as a method?
You can use a pointer to function as a member of class A. Now assign function f to g member of A.
int f(int x) {
return x+1;
}
class A {
public:
int (*g)(int);
};
int main(){
A test;
test.g = f;
cout << test.g(10); // prints 11
}
You can accomplish the same by making your function a callable objects by implementing () operator. so you can have that as member of the class, and then it can normally be used as function on the class objects.
#include <iostream>
struct do_something{
int operator()(int num){
return num;
}
};
class test{
int sum;
public:
do_something fun;
};
int main(){
test obj;
std::cout << obj.fun(10);
}
If I want my own 1D array class I can overwrite operator[] to read/write the elements. Like:
class A1D {
private:
int a[10]; // This is irrelevant - it's just to simplify the example
// The real class doesn't use a int array.
// Here I just use an int array for simplicity
public:
int& operator[] (int x) { // <--- The interesting part...
return a[x];
}
};
int main()
{
A1D a1d;
a1d[5] = 42;
std::cout << a1d[5] << std::endl;
return 0;
}
The above works fine.
But what if I want to do the same for a 2D array class.
class A2D {
private:
int a[10][10]; // This is irrelevant - it's just to simplify the example
public:
int& operator[][] (int x, int y) { // This, of cause, doesn't work
return a[x][y];
}
};
How would I code [][] to access elements in the 2D array class?
EDIT - some clarification as the first answers didn't fully do what I needed
I used int in the example above for simplicity. In the final class I won't use int so I can't return a int* and the rely on (*int)[..] for the second level.
So I'm looking for:
A2D a;
a[3][4] = SomeOtherClass; // Should call function in A2D with arg 3 and 4
SomeOtherClass x = a[3][4]; // Should call function in A2D with arg 3 and 4
You can make a proxy class which will contain a pointer to the corresponding row of the matrix. Unlike the "return the pointer" approach explained in the other answer, this one can be as well applied to 3D and multidimensional matrices.
class RowProxy {
private:
int* row;
public:
explicit RowProxy(int* row) : row(row) {}
int& operator[](int y) {
return row[y];
}
};
class A2D {
private:
int a[10][10]; // This is irrelevant - it's just to simplify the example
public:
RowProxy operator[](int x) {
return RowProxy{a[x]};
}
};
You can return a pointer to an array, for example:
class A2D {
private:
int a[10][10];
public:
int* operator[] (int x) {
return a[x];
}
};
I don't like this solution... I think it's best to have a Row and a Col class and return an object, not a raw pointer.
You can also use operator()() instead of the bracket as an alternative
class A2D {
private:
int a[10][10];
public:
int& operator()(int x, int y) {
return a[x][y];
}
};
A2D arr;
// ...
arr(3, 3) = 5;
I feel like this question must have been asked before but I couldn't find an answer from poking around on google. If it has please direct me to a link and I will remove this post.
Consider this minimal example that represents a larger problem I have. Say I created a simple "Point" and "Printer" class like so:
class Point {
public:
double x, y;
Point() {x = y = 0;}
Point(double x, double y) {
this->x = x; this->y = y;
}
};
template<typename T>
class Printer {
public:
T* mData;
int mSize;
// Constructor
Printer(std::vector<T> &input) {
mData = &input[0];
mSize = input.size();
}
// Simple Print function
void Print() {
printf(" - Showing %d items\n", mSize);
for (int i = 0; i < mSize; i++) {
const T &item = mData[i];
printf(" - Item %d: (%lf, %lf)\n", i, item.x, item.y);
}
}
};
I could use the printer class like this:
std::vector<Point> points; // fill the vector, and then...
Printer<Point> pointsPrinter(points); pointsPrinter.Print();
Now say someone else comes along and wants to use the Printer class with there own "Point" class declared like so:
class Pnt {
public:
double mX, mY;
// other stuff
};
If they try to do this:
vector<Pnt> pnts; // Fill the pnts, and then...
Printer<Pnt> pntsPrinter(pnts);
pntsPrinter.Print(); // COMPILE ERROR HERE!
Obviously this will fail because Pnt has no x or y members. Does there exist a way I can rewrite the Printer class to work with all generic user types? What I DONT want to do is copy a Pnt vector into a Points vector.
EDIT:
The only way I can think to make this work would be to pass in functions pointers. Something like this:
template<typename T>
class Printer {
public:
T* mData;
int mSize;
double* (*mXFunc) (T*);
double* (*mYFunc) (T*);
Printer(std::vector<T> &input,
double* (*xFunc) (T*),
double* (*yFunc) (T*))
{
mData = &input[0];
mSize = input.size();
mXFunc = xFunc;
mYFunc = yFunc;
}
void Print() {
printf(" - Showing %d items\n", mSize);
for (int i = 0; i < mSize; i++) {
T &item = mData[i];
printf(" - Item %d: (%lf, %lf)\n", i, *mXFunc(&item), *mYFunc(&item));
}
}
};
// Could then use it like so
inline double* getXPointVal(Point *point) {return &point->x;}
inline double* getYPointVal(Point *point) {return &point->y;}
inline double* getXPntVal(Pnt *point) {return &point->mX;}
inline double* getYPntVal(Pnt *point) {return &point->mY;}
Printer<Pnt> pntPrinter(pnts, getXPntVal, getYPntVal);
Printer<Point> pointsPrinter(points, getXPointVal, getYPointVal);
pntPrinter.Print();
pointsPrinter.Print();
The problem with this is that it looks ugly and also possibly introduces the function call overhead. But I guess the function call overhead would get compiled away? I was hoping a more elegant solution existed...
If you choose cout instead of printf to write your output, you can allow all printable types to define an overload for the << operator and use that generically inside Printer::print(). An overload could look like this:
std::ostream& operator<<(std::ostream &out, Point& p){
out << "Point(" << p.x << ", " << p.y << ")";
return out;
}
On a side note, I advise against storing a pointer to a vector's internal storage and size member. If the vector needs to reallocate, your pointer will be left dangling and invalid. Instead, you should pass the vector temporarily as a reference or keep a const reference.
You could define free (non-member) functions for each Point class you want to use. The advantage of this is that free functions can be defined later, without making changes to existing classes.
Example:
namespace A {
class Point {
public:
Point (int x, int y) : x_(x), y_(y) {}
int getX () const { return x_; }
int getY () const { return y_; }
private:
int x_, y_;
};
// in addition, we provide free functions
int getX (Point const & p) { return p.getX(); }
int getY (Point const & p) { return p.getY(); }
}
namespace B {
class Pnt {
public:
Pnt (int x, int y) : x_(x), y_(y) {}
int get_x () const { return x_; }
int get_y () const { return y_; }
private:
int x_, y_;
};
// Pnt does not have free functions, and suppose we
// do not want to add anything in namespace B
}
namespace PointHelpers {
// free functions for Pnt
int getX (Pnt const & p) { return p.get_x (); }
int getY (Pnt const & p) { return p.get_y (); }
}
// now we can write
template <class PointTy>
void printPoint (PointTy const & p) {
using PointHelpers::getX;
using PointHelpers::getY;
std::cout << getX (p) << "/" << getY (p) << std::endl;
}
A::Point p1 (2,3);
B::Pnt p2 (4,5);
printPoint (p1);
printPoint (p2);
If the free functions live in the same namespace as the corresponding class, they will be found by argument-dependent name lookup. If you do not want to add anything in that namespace, create a helper namespace and add the free functions there. Then bring them into scope by using declarations.
This approach is similar to what the STL does for begin and end, for instance.
Don't expect from the templates to know which members of given class/structure corresponds to your x and y...
If you want to create generic solution you could tell your printer function how to interpret given object as your Point class using e.g. lambda expression (c++11 solution):
#include <iostream>
class Point {
public:
double x, y;
Point() {x = y = 0;}
Point(double x, double y) {
this->x = x; this->y = y;
}
};
class Pnt {
public:
double mX, mY;
// other stuff
};
template <class P, class L>
void Print(const P &p, L l) {
Print(l(p));
}
void Print(const Point &p) {
std::cout << p.x << ", " << p.y << std::endl;
}
int main() {
Print(Point(1, 2));
Print(Pnt{4, 5}, [](const Pnt &p) -> Point {return Point(p.mX, p.mY);});
}
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 } );
}
I would like someone to explain me the "name::name" syntax and how it is used on C++ programming. I have been looking through but I don't get it yet. Thanks for help.
Here is context code:
void UsbProSender::SendMessageHeader(byte label, int size) const {
Serial.write(0x7E);
Serial.write(label);
Serial.write(size);
Serial.write(size >> 8);
}
:: is the scope resolution operator.
std::cout is the name cout in the namespace std.
std::vector::push_back is the push_back method of std::vector.
In your code example:
void UsbProSender::SendMessageHeader(byte label, int size) const {
Serial.write(0x7E);
Serial.write(label);
Serial.write(size);
Serial.write(size >> 8);
}
UsbProSender::SendMessageHeader is providing the definition for the SendMessageHeader method of the UsbProSender class.
Another (more complete) example:
class Bar {
int foo(int i); // forward declaration
};
// the definition
int Bar::foo(int i) {
return i;
}
It is operator for scope resolution.
Consider that code
class A { public: void f(){} };
class B { public: void f(){} };
class C : public A, public B {};
int main(int argc, char *argv[])
{
C c;
// c.f(); // ambiguous: which one of two f() is called?
c.A::f(); // OK
c.B::f(); // OK
return 0;
}