gpt4 book ai didi

c++ - 奇怪的是,SFINAE 不可能进行递归模板调用

转载 作者:搜寻专家 更新时间:2023-10-31 02:15:04 25 4
gpt4 key购买 nike

编辑:问题已解决,只是函数声明顺序错误。

当我试图解决一个乍一看似乎很微不足道的问题时,我偶然发现了我无法解释的行为。

我想递归地处理任意整数数组,当然我必须以某种方式停止递归。由于使用模板函数(如

template<typename T, int N> foo<T, 0>(void)

),我试图用 SFINAE 伪造它。但是当我想从第一个函数调用第二个 SFNIAE 函数时,出现编译器错误。完整代码示例:

#include <algorithm>
#include <iostream>

using namespace std;

// -------------------------------------------------------------
template<typename T, int N>
void foo(T const& param, typename enable_if<N != 0, int>::type* = 0)
{
cout << "recursive step " << N << endl;

/* --- This was, what I desired: --- */
//foo<T, N - 1>(param);

/* --- THIS IS CAUSING AN ERROR! --- */
foo<T, 0>(param);
}

// -------------------------------------------------------------
template<typename T, int N>
void foo(T const& param, typename enable_if<N == 0, int>::type* = 0)
{
cout << "finish recursion" << endl;
}


// =============================================================
int main()
{
int a[5] = {0, 1, 2, 3, 4};
foo<decltype(a), 5>(a);

/* --- SAME CALL AS WITHIN foo(), BUT CAUSING NO ERROR! --- */
foo<decltype(a), 0>(a);
}

编译器告诉我: main.cpp:9: Fehler: 在“struct std::enable_if”中没有名为“type”的类型所以他似乎无法解决第二个功能。但是,如果我从 main() 调用函数,这不是问题。

第一次来SFINAE,希望没有犯小错。感谢所有读到这里的人!

最佳答案

我对 Clang's helpfulness 感到惊喜关于这个:

main.cpp:14:5: error: call to function 'foo' that is neither visible in the template definition nor found by argument-dependent lookup    foo(param);    ^main.cpp:29:5: note: in instantiation of function template specialization 'foo' requested here    foo(a);    ^main.cpp:19:6: note: 'foo' should be declared prior to the call sitevoid foo(T const&, typename std::enable_if::type* = 0)     ^

I mean, it's just one step away from logging in on Stack Overflow and giving the answer itself. Anyway.

Add the declaration of the second function above the first one, so you can call it from therein:

template<typename T, int N>
void foo(T const&, typename std::enable_if<N == 0, int>::type* = 0);

请注意,您还必须从定义中删除默认参数。

关于c++ - 奇怪的是,SFINAE 不可能进行递归模板调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39161810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com