[英]order of functions in Variadic templates
以下代碼正常運行! 但我的問題是理論上如果我們在命名空間細節中反轉兩個版本的index_of
,編譯器說沒有函數模板匹配但為什么?
#include <iostream>
using namespace std;
template <typename... Args>
class Pack{
public:
Pack(){}
};
template <typename T, typename Arg, typename... Args>
bool contains(Pack<Arg, Args...> p)
{
Pack<Args...> n;
return std::is_same_v<T,Arg> || contains<T>(n);
}
template <typename T>
bool contains(Pack<> p){
return false;
}
namespace detail{
template <typename T>
int index_of(Pack<> p, int index){
return -1;
}
template <typename T, typename Arg, typename... Args>
int index_of(Pack<Arg, Args...> p, int index = 0){
if(is_same_v<T,Arg>) return index;
Pack<Args...> rest;
return index_of<T>(rest, index+1);
}
}
template <typename T, typename... Ts>
int index_of(Pack<Ts...> p)
{
return detail::index_of<T>(p);
}
int main()
{
Pack<int,string,double> p;
cout << contains<int>(p) << endl;
cout << contains<char>(p) << endl;
cout << index_of<int>(p) << endl;
}
第二個index_of
本身調用index_of
。 如果它首先列出,那么另一個index_of
是不可見的,所以它只能是一個遞歸調用; 但只有一種類型仍然存在,遞歸調用是不可行的。
當它列在第二個時, index_of
兩個版本都在該調用的范圍內。
基本上,它歸結為一個函數必須在它被調用之前聲明的事實。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.