0

I've started delving into C++11 but I'm having trouble understanding the correct contexts where I can use bind and lambdas.

Specifically, I want to create a class which takes in pointers to some classes and an int ID telling which usable class pointer has been passed. All other pointers are set to NULL. The function accepts a few pointers, and rather than defining a whole bunch of ClassX* clX = NULL I want to the function to take in only one pointer and the appropiate ID.

I've put my "testing" file below. Can anyone see what is wrong with it? I'm still pretty new at doing C++ (started in MATLAB) so if you see any style problems please tell me as well.

#include <iostream>
#include <functional>

using namespace std;
using namespace std::placeholders;

class ClassB1 {
public:
    ClassB1() {}
};
class ClassB2 {
public:
    ClassB2() {}
};
class ClassB3 {
public:
    ClassB3() {}
};

class ClassA {
public:
    ClassA(ClassB1* b1, ClassB2* b2, ClassB3* b3, int ID) {
        //Find look at ID and do something with appropiate class pointer
    }
};

int main()
{
    ClassA lambdaFunc = [] (ClassB1* _b1, int id) { return ClassA::ClassA(_b1, NULL, NULL, id)};
    ClassA bindFunc = bind(ClassA::ClassA,_1,NULL,NULL,_2);
    ClassB1 _b1 = ClassB1();
    _id = 1;
    lambdaFunc(&_b1, _id);
    bindFunc(&_b1, _id);
}
2
  • Didn't realise the order of classes in this is important; edited so that ClassA is below ClassB1-3 Commented Jul 29, 2014 at 2:26
  • The normal solution is to use overloading and default arguments: A(B1* b1 = 0, B2* b2 = 0, B3* b3 = 0); A(B2* b2 = 0, B3* b3 = 0); A(B3* b3 = 0); - no ID needed. The compiler will figure out which types you've passed. With templates, you can even avoid the need to order your arguments but that code won't fit in a comment. Commented Jul 29, 2014 at 8:48

1 Answer 1

1

If for some strange reason you insist on using a lambda for this problem, make it

  auto lambdaFunc = [] (ClassB1* _b1, int id) {
    return ClassA(_b1, NULL, NULL, id);
  };
  ClassB1 _b1;
  int _id = 1;

  ClassA a = lambdaFunc(&_b1, _id);

Though I must admit I don't quite understand the point of the exercise.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a simplification of a prompt I need that needs to display different class info based on the class it was called from (they all pass this). Though now I realise that this is kind of a wonky way to do it...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.