2

So basically I want to create a set of Function objects. In python if we do:

def func():
    print "a"

a = func
b = func
fset = set()
fset.insert(a)
fset.insert(b)

In this case fset will have only one function since both a and b are same in python. But in C++, if I create function objects for same function both a and b will be two different objects of a set. Is there any way that two objects of same function be same?

In C++:

void func(){
    cout << "a";
}

function<void()> a = bind(func);
function<void()> b = bind(func);

Now I want if a or its pointer is already present in the set, b should not be added.

9
  • 1
    a and b are essentially two pointers to the same object, not two instances of the same class. You can have std::set<std::function<void()>*>, or possibly a smart pointer - it'll behave in a similar manner. Commented Nov 23, 2018 at 5:22
  • But in this case also every time creating a pointer of function<void()> a = function(); function<void()> b = function(); Both a and b will still have different pointers right? Commented Nov 23, 2018 at 5:23
  • 2
    A set, by definition, contains values distinct from one another. It's not clear what you're talking about here, when you suggest that you are putting the "same function" into a set as two different objects. Perhaps you should back up your question with some C++ code to illustrate your problem. Commented Nov 23, 2018 at 5:25
  • You say "creating a pointer", but your code doesn't actually create any pointers. It's also not clear what you mean by function() - that doesn't appear syntactically valid and likely won't compile. Commented Nov 23, 2018 at 5:25
  • @IgorTandetnik they are talking about your comment which stores std::function<void()>* Commented Nov 23, 2018 at 5:26

1 Answer 1

1

If you have only void functions(or all functions have the same signature), use simply C type function pointers as std::sets's template type.

This will work and as a plus no type erasure overheads of std::function.

void func() {}
void func2() {}

using fPtrType = void(*)(); // convenience type  

int main()
{
    std::set<fPtrType> fset;
    fPtrType a = func;
    fPtrType b = func;
    fset.emplace(a);
    fset.emplace(b);
    fset.emplace(func2);

    std::cout << fset.size();  // prints 2
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Will this also work if both a and b have a different scope?
@250 Did you mean this.

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.