I have a very simple function
template<typename T>
bool is_element(const std::vector<T> & vec, T el)
{
return (std::find(vec.begin(), vec.end(), el) != vec.end());
}
Run Code Online (Sandbox Code Playgroud)
that is supposed to just check if an element exists in a vector. But I run into problems when for example el is an unsigned long and vec is an integer vector. The template types are different initially, but the same after implicit conversion. Is there any elegant way to deal incorporate implicit conversion into templates without doing a bunch of function overloading?
您可以T使用第一个参数来推论,而通过将第二个参数置于不可推论的上下文中来抑制类型推导:
template<class T>
struct suppress_deduction {
using type = T;
};
template<class T>
using suppress_deduction_t = typename suppress_deduction<T>::type;
template<typename T>
bool is_element(const std::vector<T> & vec, suppress_deduction_t<T> el)
{
return (std::find(vec.begin(), vec.end(), el) != vec.end());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |