2017-03-17 76 views
0

我剛想出一個想法來構建像boost :: signals這樣的信號庫的簡單實現。C++ variadic模板中的編譯器錯誤

我寫了一個簡單的模板,但在試圖調用算符()火災所有的回調時,我得到一個錯誤:

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; 

} 

任何想法是這個編譯器錯誤原因(錯誤C2062型「詮釋」意外)

回答

2
void operator() (args...) 
{ 
    for (const auto & cb : m_callbacks) 
     cb(args...); 
} 

在上面的代碼片段args型包 - 你需要擴展它裏面cb之前,給它一個名字:

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