1

So I have an overloaded templated function that needs to be passed down to a thread. I don't know how to distinguish overloaded functions to a function pointer.

template<typename T>
void DetectChange(T& variable, T& notify) {             // must be a thread, else it's useless
    T original = variable;

    while (true) {
        if (variable != original) {                     // change detected
            notify = variable;                          // send notification
            variable = original;                        // reset to original
        }
    }
}

template<typename T>
void DetectChange(T& variable, void (* notify)()) {     // must be a thread, else it's useless (template, function pointer)
    T original = variable;

    while (true) {
        if (variable != original) {                     // change detected
            notify();                                   // do notification function
            variable = original;                        // reset to original
        }
    }
}

int main() {
    int x = 3;
    void(*function)();
    function = &DetectChange;               // how to distinguish which overloaded templated function
    std::thread detect = std::thread(&function, x, doSomething);
    x++;                                    // change variable

    return 0;
}
razorozx
  • 73
  • 1
  • 4
  • 1
    Neither overload is a function of signature `void()` – W.F. Dec 03 '17 at 19:12
  • 1
    You need to declare `function` with the exact signature of the overload you want to assign to it, for instance `void (*function)(int&, void (*)());` (assuming `doSomething` is a function with a `void` return value and no arguments). And remove `&` when passing `function` to the `std::thread` constructor – Remy Lebeau Dec 03 '17 at 19:12
  • @RemyLebeau Thanks! However, trying to assign "&DetectChange" as well as "&DetectChange " gives me a syntax error as well as "unable to resolve function overload" – razorozx Dec 03 '17 at 19:27
  • 1
    @razorozx [works fine for me](https://ideone.com/QsIap9), using a `typedef` for the function pointer variable – Remy Lebeau Dec 03 '17 at 19:48
  • @RemyLebeau Oh, I see what I did wrong. How is ref(x) different from &x? Aren''t they just references to the same thing? – razorozx Dec 03 '17 at 20:16
  • 1
    @razorozx `&x` is an `int*` pointer, not an `int&` reference. A pointer and a reference are similar but different types – Remy Lebeau Dec 03 '17 at 20:37

1 Answers1

1

Your problem is that function doesn't match either overload. function is declared taking no arguments but both available overloads take at least two. And the function-pointer type has to match down to references etc.

void (*ptr)(int &, int&) = &DetectChange;

Of course that would fail to compile because int isn't a valid T but it should give you the idea.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23