[英]What type of std::function to I need to be able to assign it to either std::upper_bound or std::lower_bound
我有一個std::vector<double> m_x;
在某些時候,我要么需要std::lower_bound(m_x.begin(), m_x.end(), x)
作為double x
,要么需要std::upper_bound(m_x.begin(), m_x.end(), x)
我想要的是某種
std::function<std::vector<double>::const_iterator(std::vector<K>::const_iterator, std::vector<double>::const_iterator, double)> bound;
然后我可以分配
bound = whatever ? std::upper_bound : std::lower_bound;
然后調用bound(m_x.begin(), m_x.end(), x)
只有我無法解決條件中的語法。 我也不確定bound
的類型是否正確。 有任何想法嗎?
更新:
當我在鏈接問題( 如何聲明對標准算法的引用? )中采用該技術時,即
using iterator = decltype(m_x.begin());
using overload = iterator(*)(iterator, iterator, const double&);
auto me = static_cast<overload>(std::upper_bound<iterator, iterator, const K&>);
我得到錯誤(msvc)
error C2440: 'static_cast': cannot convert from 'overloaded-function' to 'overload'
您以錯誤的方式將答案應用於副本。
// assuming function template<typename K>
using Iterator = decltype(m_x.begin());
using Overload = Iterator(*)(Iterator, Iterator, const K&);
auto me = bound
? static_cast<Overload>(std::upper_bound<Iterator>)
: static_cast<Overload>(std::lower_bound<Iterator>);
K findValue; // set here
// need to dereference this because `me` returns an iterator
auto value = *me(m_x.begin(), m_x.end(), findValue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.