使用成员函数指针作为参数的可变参数模板

时间:2014-11-09 11:51:17

标签: c++ templates variadic-templates

我在线观看了几个例子,但我不明白为什么不能编译.. 我正在尝试做的是将类Object的成员函数传递给具有所述对象的向量的类,并且具有带有模板化参数的函数作为参数被调用... 例如:

template <typename ...Args_t>
bool objectsDo(bool (Object::*func)(Args_t...), Args_t&&... args) {
    for (int i = 0 ; i < OBJECTS ; ++i) {
        if (!m_objects[i]->*func(std::forward<Args_t>(args)...)) {
            return false;
        }
    }
    return true;
}

但我尝试的每个功能,即使是无参数的功能:

error: no instance of function template "objectsDo" matches the argument list
            argument types are: (bool ())
                objectsDo(&Object::close);

我的用法是:

            objectsDo(&Object::close);

编辑: 正如Columbo所建议的那样,我现在正在向函数发送地址,但在使用参数发送时仍然会出现错误,例如:

  error: no instance of function template "objectsDo" matches the argument list
            argument types are: (bool (Object::*)(int, char), int, char)

1 个答案:

答案 0 :(得分:7)

我假设您调用这样的函数:

int main()
{
    int i; char c;
    objectsDo(&Object::close, i, c);
}

问题是随后推断出模板参数:

template <typename ...Args_t>
bool objectsDo(bool (Object::*func)(Args_t...), Args_t&&... args)
对于第一个参数,

Args_t被推断为int, char,而对于第二个参数,推断为int&, char&。这是因为通用引用的内部工作:它适用于引用折叠。

使用另一个参数包作为尾随参数:

template <typename ...Args_t, typename... Args>
bool objectsDo(bool (Object::*func)(Args_t...), Args&&... args)
{ /* […] */ }

或者将尾随参数设为非推导上下文:

template <typename T> struct identity {using type = T;};
template <typename T>
using identity_t = typename identity<T>::type;

template <typename ...Args_t>
bool objectsDo(bool (Object::*func)(Args_t...), identity_t<Args_t>... args){
    // […]
}
相关问题