jeudi 8 juin 2017

C++ How to bind and invoke a templated type method

I'm trying to understand the syntax to bind to a templated type's method. This seemed similar to my question, but didn't seem to give an example of binding and calling a templated type method.

Here's my code sample:

#include <functional>
#include <iostream>

using namespace std;

void DidSomething(int x)
{
    cout << "Did something x = " << x << endl;
}

template <typename T>
class Outer
{
public:
    void StartSomething()
    {
        Inner inner;

        // below lines cause
        // error C2893 Failed to specialize function template
        //'unknown-type std::invoke(_Callable &&,_Types &&...)'

        auto fnGlobal = std::bind(&::DidSomething);
        inner.DoOneThing(fnGlobal);

        auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
        inner.DoOneThing(fnMethod);
    }

    void DidSomething(int x)
    {
        cout << "Did something x = " << x << endl;
    }

    // example typedef, the actual callback has a lot of args (5 args)
    typedef std::function<void(int)> DidSomethingCallback;

private:

    class Inner
    {
    public:
        void DoOneThing(DidSomethingCallback fnDidSomething)
        {
            fnDidSomething(3);
        }
    };

    T t;
};

int main()
{
    Outer<bool> outer;
    outer.StartSomething();

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire