我正在编写一个带有迭代器标签的函数来处理不同的迭代器。但是,我想做一个后备,所以使用了一个模板。我本以为模板的优先级会比转换为基类型的优先级低。我错了:
#include <iterator>
#include <iostream>
using namespace std;
void test(std::forward_iterator_tag) {
cout << "forward_iterator_tag" << endl;
}
void test(std::random_access_iterator_tag) {
cout << "random_access_iterator_tag" << endl;
}
template <typename TAG>
void test(TAG x) {
cout << "other tag" << endl;
}
int main(){
test(bidirectional_iterator_tag{});
return 0;
}
我本以为这个程序会打印出forward_iterator_tag
,但是它在other tag
上是匹配的。
我试图通过阅读Best viable function来理解这一点,但我实际上并没有看到(或者我只是不理解),它会告诉我哪个应该先取。考虑到这一点,我意识到我可以使用...
参数而不是模板,因为省略号参数具有最低的优先级,但我想了解这里发生了什么以及为什么。
发布于 2021-10-23 21:30:26
因此,模板参数是更好的匹配,因为它可以转换为确切的类型。与派生类型相比,完全匹配的类型胜出。
要“修复”,请使用省略号作为参数,当所有其他选项都失败时,它将被选中。
#include <iterator>
#include <iostream>
using namespace std;
void test(std::forward_iterator_tag) {
cout << "forward_iterator_tag" << endl;
}
void test(std::random_access_iterator_tag) {
cout << "random_access_iterator_tag" << endl;
}
void test(...) {
cout << "other tag" << endl;
}
int main(){
test(bidirectional_iterator_tag{});
return 0;
}
它现在将输出我想要的forward_iterator_tag
。这在Ranking of implicit conversion sequences中进行了描述,其中声明:
重点是我的。
https://stackoverflow.com/questions/69693928
复制相似问题