我有一類函數添加:通重載成員函數的可變參數模板功能
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