2016-11-30 82 views
3

說的對象我有這樣的功能:轉換算符對類型功能

template <typename T> 
void foo(function<T(const T&, const T&)> op, const T& lhs, const T& rhs) { 
    cout << op(lhs, rhs) << endl; 
} 

這是legal code

function<int(const int&, const int&)> op = plus<int>(); 

foo(op, 13, 42); 

但是,當我這樣做:

foo(plus<int>(), 13, 42) 

我得到錯誤:

No matching function for call to foo(std::plus<int>, int, int)

爲什麼我可以從plus<int>()初始化function<int(const int&, const int&)>類型的對象,但是我無法將plus<int>()轉換成類型爲function<T(const T&, const T&)>的參數?這是否與模板有關?

+3

隱式類型轉換在模板參數推演期間不起作用。 – Arunmu

+1

@Arunmu我認爲這個規則有例外:[例子](http://melpon.org/wandbox/permlink/ld8NyDotgjK7B7WT) –

+0

@Arunmu這是它的工作原理,如果我刪除模板:http:// ideone.com/bfjy3p那麼我怎麼知道'plus ()'和'function 之間的轉換是隱式的? –

回答

2

從標準節14.8.1.6報價:

Implicit conversions (Clause 4) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction.

因爲模板參數沒有作出明確規定,這不會工作你的情況。編譯器需要做一個演繹。因此按照以上所述,它不會執行從仿函數到std::function的隱式轉換。

所以,你可以做(​​正如在評論中提及的@flatmouse):

foo<int>(plus<int>(), 13, 42);

這工作,因爲有需要,因爲所有的模板參數都明確地進行沒有模板參數推導指定。根據標準的上述引用,隱式轉換應該適用於此。

+0

感謝標準的報價,這是一個很好的答案。我會很快接受... –

+0

很高興提供幫助。謝謝。 – Arunmu