【发布时间】:2019-08-05 13:43:21
【问题描述】:
在我的课堂上,我有 2 种算法应该应用,具体取决于容器是否支持 lower_bound。
template <class T>
class SmartContainerHandler{
....
template <class Q=T>
typename std::enable_if< std::is_member_function_pointer<decltype(&Q::lower_bound)>::value >::type
foo_impl(int k, double _ = 0)
{
auto r = _t.lower_bound(k);
std::cout << "has lower_bound" << (r == _t.end() ? -1 : *r) << std::endl;
}
template <class Q=T>
typename std::enable_if<! std::is_member_function_pointer<decltype(&Q::lower_bound)>::value >::type
foo_impl(int k)
{
std::cout << << "no lower_bound, just a key:" << k << std:: endl;
}
例如,我想使用SmartContainerHandler<std::set<int> > 或SmartContainerHandler<std::vector<int> > 进行实例化
lower_bound 有 2 个签名我的问题
template< class K > iterator lower_bound(const K& x);
template< class K > const_iterator lower_bound(const K& x) const;
(尝试编译没有成功auto m = &std::set<int>::lower_bound)
在我的特殊情况下,我不关心 const 签名,但为了更通用的问题:如果提供了 2 个或更多签名,如何检查方法是否存在?
【问题讨论】:
-
你想要一种方法来区分无重载/一个重载/两个重载(例如,const / non-const)?或者只是一种区分无重载/一个或多个重载的方法?
-
@Holt 对我来说最好的——让编译器提供最好的重载。但我从表达式
&Q::lower_bound了解到这是不可能的。所以 const/non-const 是指定正确选择的好方法。