[英]order of functions in Variadic templates
The following code is working! 以下代码正常运行! But my question is theoretical if we inverse the two version of index_of
in the namespace detail, the compiler says that no function template is matching but why? 但我的问题是理论上如果我们在命名空间细节中反转两个版本的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;
}
The second index_of
itself calls index_of
. 第二个index_of
本身调用index_of
。 If it's listed first, then the other index_of
is not visible, so it can only be a recursive call; 如果它首先列出,那么另一个index_of
是不可见的,所以它只能是一个递归调用; but the recursive call is not viable once only one type remains. 但只有一种类型仍然存在,递归调用是不可行的。
When it's listed second, both versions of index_of
are in scope for that call. 当它列在第二个时, index_of
两个版本都在该调用的范围内。
Basically, it boils down to the fact that a function has to be declared before it can be called. 基本上,它归结为一个函数必须在它被调用之前声明的事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.