I have these two functors:
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;
};
However, if i use the second functor in a templated function. I got errors:
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
}
How can i call the functor's operator()
from the test
function?
It can't deduce the return type of operator()
, K
, in any way, so you need to explicitly specify the template arguments. The reason your second attempt doesn't work is because you need to include the template
keyword:
K key2 = k.template operator()<T,K>(item, 2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.