[英]templated functor called with templated types
我有兩個函子:
template<typename T>
struct identity {
const T &operator()(const T &x) const {
return x;
}
};
template<typename KeyFunction>
class key_helper {
public:
key_helper(const KeyFunction& get_key_) : get_key(get_key_) { }
template<typename T, typename K>
const K operator()(const T& x, const int& n) {
return get_key(x);
}
private:
KeyFunction get_key;
};
但是,如果我在模板函數中使用第二個函子。 我有錯誤:
template<typename T, typename K>
void test(T item, K key) {
identity<T> id;
key_helper<identity<T> > k(id);
K key2 = k(item, 2); // compiler cannot deduce type of K
key2 = k.operator()<T, K>(item, 2); // expected primary-expression before ',' token
}
如何從test
函數調用函子的operator()
?
它無法以任何方式推論operator()
的返回類型K
,因此您需要顯式指定模板參數。 您第二次嘗試不起作用的原因是,您需要包括template
關鍵字:
K key2 = k.template operator()<T,K>(item, 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.