有谁能解释一下could网站的样本中的几个点吗?该技术描述了函数重载取决于迭代器类型。前两种类型与“使用”是明确的理解。这些问题涉及高级管理小组的职能:
1. could you explain the using of third template parameter in second function alg and the comment there:
"typename = void> // dummy值以避免模板重新定义错误“
代码在这里(tags):
template<typename Condition, typename T = void>
using EnableIf_t = typename std::enable_if<Condition::value, T>::type;
template<typename Iterator, typename IteratorTag>
using IsSameIteratorCond =
std::is_same<IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>;
template<
typename BDIter,
typename = EnableIf_t<IsSameIteratorCond<BDIter, std::bidirectional_iterator_tag>>>
void alg(BDIter, BDIter)
{
std::cout << "alg() called for bidirectional iterator\n";
}
template<
typename RAIter,
typename = EnableIf_t<IsSameIteratorCond<RAIter, std::random_access_iterator_tag>>,
typename = void> // dummy value to avoid template re-definition error
void alg(RAIter, RAIter)
{
std::cout << "alg() called for random-access iterator\n";
}
int main()
{
std::vector<int> v;
alg(v.begin(), v.end());
std::list<int> l;
alg(l.begin(), l.end());
}发布于 2015-06-03 09:05:48
typename = ...声明一个未命名的模板参数。客户端代码仍然可以覆盖它,但是参数不能在函数定义中使用。之所以在这里使用它,是因为第二个模板参数用于利用SFINAE,而不是计算要在定义中使用的类型。alg将尝试定义相同的函数模板。使用默认值和虚拟参数对我来说很难看,我更喜欢使用标记分派:
template<typename BDIter>
void alg(BDIter, BDIter, std::bidirectional_iterator_tag)
{
std::cout << "alg() called for bidirectional iterator\n";
}
template <typename RAIter>
void alg(RAIter, RAIter, std::random_access_iterator_tag)
{
std::cout << "alg() called for random-access iterator\n";
}
template <typename It>
void alg(It a, It b)
{
return alg(a, b, typename std::iterator_traits<It>::iterator_category{});
}发布于 2015-06-03 09:03:32
std::bidirectional_iterator_tag,对于第二个重载,必须等于std::random_access_iterator_tag。https://stackoverflow.com/questions/30615190
复制相似问题