Compiler error in c++ variadic template

344 Views Asked by At

I just came up with an idea to build a simple implementation of signals lib like boost::signals.

I wrote a simple template for this but I'm getting an error when trying to invoke oparator() to fire all callbacks:

template <typename funcDef>
struct Connection
{
    typename std::vector<std::function<funcDef>>::iterator connectionItem;
};

template <typename funcDef>
class Signal;

template <typename retType, typename... args>
class Signal<retType(args...)>
{
    using return_type = retType;
    using argument_type = std::tuple<args...>;
public:
    Signal() {};
    ~Signal() {};

    Connection<retType(args...)> connect(std::function<retType(args...)> callback)
    {
        Connection<retType(args...)> connection;
        m_callbacks.push_back(callback);
        connection.connectionItem = std::prev(m_callbacks.end());

        return connection;
    }

    void disconnect(Connection<retType(args...)> connection) { m_callbacks.erase(connection.connectionItem); }

    void operator() (args...) 
    { 
        for (const auto & cb : m_callbacks) 
            cb(args...); // this generates compiler error: Error C2062 type 'int' unexpected    

    }

private:
    std::vector<std::function<retType(args...)>>  m_callbacks;
};


int sum(int a, int b){ return a + b; }
int sub(int a, int b){ return a - b; }

int main()
{

    Signal<int(int, int)> sig;
    auto c1 = sig.connect(sum);
    auto c2 = sig.connect(sub);

    sig(2, 2);

  return 0;

}

Any ideas what's the reason for this compiler error (Error C2062 type 'int' unexpected)

1

There are 1 best solutions below

0
Vittorio Romeo On
void operator() (args...) 
{ 
    for (const auto & cb : m_callbacks) 
        cb(args...);
}

args in the above snippet is a type pack - you need to give it a name before expanding it inside cb:

void operator() (args... xs) 
{//              ^^^^    ^^
 //              type    name
    for (const auto & cb : m_callbacks) 
        cb(xs...);
}