【问题标题】:Template member function error: clang doesn't match any member function模板成员函数错误:clang 不匹配任何成员函数
【发布时间】:2013-05-17 20:31:31
【问题描述】:

我已经编写了以下模板成员函数,但我无法调用它而不会被编译器出错:

template <class T, class A>
auto tpool::enqueue(T&& func, std::vector<A>&& args)
-> std::vector<std::future<decltype(std::forward<T>(func)(decltype(std::forward<A(args))::value_type))>>
{
    //...
}

tpool tp();
auto f = [] (int) { /* ... */ };
std::vector<int> args; 

tp.enqueue(f, args);

我通过 clang 收到以下错误:

test_cpp.cpp:144:5: error: no matching member function for call to 'enqueue'
    tp.enqueue(f, args);

test_cpp.cpp:107:13: note: candidate template ignored: substitution failure [with T = <lambda at test_cpp.cpp:140:11> &, A = int]: no matching function for call to 'forward'
auto tpool::enqueue(T&& func, std::vector<A>&& args)

【问题讨论】:

  • tpool tp(); 是指tpool tp;
  • 你有几个语法错误。 std::forward&lt;A(args) 例如

标签: c++ templates c++11 clang


【解决方案1】:
template <class T, class A>
auto tpool::enqueue(T&& func, std::vector<A>&& args)

这使得args 成为一个右值引用,它只接受右值,但在

std::vector<int> args; 
tp.enqueue(f, args);

args 是一个左值,因此候选者被忽略。

注意T&amp;&amp; func 允许绑定左值,因为模板替换可以让T 本身成为左值引用,然后我们就有(T&amp;)&amp;&amp; == T&amp;。但这对于args 是不可能的,因为无论A 是什么,std::vector&lt;...&gt;&amp;&amp; 始终是向量的右值引用。


如果您不打算复制或修改 args,则可以传递一个 const 引用:

template <class T, class A>
auto tpool::enqueue(T&& func, const std::vector<A>& args)

您也可以通过不指定 args 必须是向量来允许完美转发:

template <class T, class V>
auto tpool::enqueue(T&& func, V&& args)
    -> std::vector<std::future<decltype(func(args.front()))>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多