我有一类函数添加:通重载成员函数的可变参数模板功能
class Pool {
public:
Pool() {};
template<class F, class... A>
auto add(F&& f, A&&... args) -> std::future<typename std::result_of<F(A...)>::type>
{
// return empty placeholder, for the sake of this code example
std::future<typename std::result_of<F(A...)>::type> ret;
return ret;
};
};
应该采取与它的任何参数的功能,把它添加到一个线程池,并返回的未来该函数的结果类型。
和我将用它的类:
class MyClass {
public:
string doIt(string) { return string("a"); };
string doIt(int, string) { return string("b"); };
void test() {
Pool myPool;
string a("test");
myPool.add(&MyClass::doIt, a); // Error
};
};
其中给出一个编译器错误:
Error 1 error C2914: 'Pool::add' : cannot deduce template argument as function argument is ambiguous MyClass.cpp 94
现在的问题是(我认为),编译器不能推断出我超载想用。类似于Overloaded function as argument of variadic template function。我也不是100%清楚为什么我不得不使用“&”作为类成员函数,但是如果我传入一个自由函数,则不需要使用&符号)。 反正我也试过在上述答复中提到的解决方法:
struct doIt_wrapper {
template <typename... T>
auto operator()(T... args) -> decltype(doIt(args...)) {
return doIt(args...);
}
};
,然后修改MyClass的::测试()来:
void test() {
Pool myPool;
string a("test");
myPool.add(doIt_wrapper(), a);
};
但它也给了我一个编译器错误:
error C2893: Failed to specialize function template 'unknown-type doIt_wrapper::operator()(T...)' C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap 58
我也尝试了一些变体,如myPool.add(doIt_wrapper<string>()
和有/没有'&',但它们都会产生一个或另一个编译器错误。
我觉得我还没有完全理解这个问题,如果有人能说清楚,我会很高兴。此外,我正在寻找适当的解决方案来解决这个问题。事实并非如此,只要没有两个具有相同名称的函数,只有这样,所有事情都会崩溃,而没有适当的通用解决方案?
编辑:修正了一些错别字,并上载一个小例子,在这里:http://ideone.com/eX1r1l
第一次演员还需要绑定'this'。 – 0x499602D2 2014-10-17 15:10:41
谢谢你的lambda和铸造解决方案!他们确实都工作。现在就必须决定哪个是最不丑陋的,或者更确切地说,它以最清晰的方式表现出意图。 – Ela782 2014-10-17 19:51:06
@ Ela782:lambda的第二种方式对我来说似乎最清晰(您可能更喜欢'[=]'捕获)。 – Jarod42 2014-10-17 20:15:14