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.

250
  • 581
  • 5
  • 17
  • 1
    `a` and `b` are essentially two pointers to the same object, not two instances of the same class. You can have `std::set*>`, or possibly a smart pointer - it'll behave in a similar manner. – Igor Tandetnik Nov 23 '18 at 05:22
  • But in this case also every time creating a pointer of function a = function(); function b = function(); Both a and b will still have different pointers right? – 250 Nov 23 '18 at 05: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. – paddy Nov 23 '18 at 05: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. – Igor Tandetnik Nov 23 '18 at 05:25
  • @IgorTandetnik they are talking about _your_ comment which stores `std::function*` – paddy Nov 23 '18 at 05:26
  • Well, yes - but *their* code doesn't manipulate pointers, so it's not clear what they plan to put into that set. – Igor Tandetnik Nov 23 '18 at 05:26
  • Possible duplicate of [Why are these constructs using pre- and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – Swordfish Nov 23 '18 at 05:31
  • Possible duplicate of [std::set has duplicate entry](https://stackoverflow.com/questions/29119602/stdset-has-duplicate-entry) – lost_in_the_source Nov 23 '18 at 05:36
  • @paddy I have added some C++ code to illustrate the problem. – 250 Nov 23 '18 at 05:42

1 Answers1

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;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88