gpt4 book ai didi

c++ - 基于范围的循环和内联函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:16 26 4
gpt4 key购买 nike

我这里有这段代码。

#include <iostream>
using namespace std;

template <typename T> inline T bigArry(const T data[5])
{
T level = data[0];
for(T item : data) // error C2143: syntax error : missing ',' before ':' (1st)
{ //error C2143: syntax error : missing ';' before '{' (3rd)
if(level<item){ level=item; }
}
return level;
}

int main()
{
int data[5]={//five variables}
cout << bigArry(data);//see reference to function template instantiation 'T bigArry<int>(const T [])' being compiled with [ T=int] (2nd)

return 0;
}

函数 bigArry() 返回 5 个元素数组中的最大值。

问题是,当我使用基于范围的循环时,它会给我代码中提到的错误。但是当我使用通常的 for 时,一切都会恢复正常。我的意思是,语法对我来说看起来不错,我看不出问题所在。我正在使用 Visual Studio 2010。

我想问的另一件事是关于内联函数。目前我正在阅读 C++ Primer Plus 第 6 版。我什么时候知道函数太大而无法内联?代码应该有多短有标准吗?或者,我们是否在“认为”没问题时使用内联函数?

最佳答案

参数data不是函数模板中的数组。它实际上是一个指针。

这个函数

template <typename T> inline T bigArry(const T data[5])

与此完全相同:

template <typename T> inline T bigArry(const T *data)

完全没有区别。

这就是您的代码出现编译错误的原因。

这里有几个修复:

  • 您可以通过引用接受参数,如:

    template <typename T> 
    inline T bigArry(const T (&data)[5]) //NOTE &

    那应该行得通。但这看起来很麻烦。也许,用下一个。

  • 或者您可以使用这个(如@yzt 所建议的那样):

    template <typename C> 
    inline auto bigArry(C const & data) -> decltype(data[0])

    这比上面的(和下面的)更干净,也更灵活。除了传递数组外,您还可以传递任何 容器,只要data[0] 即可。定义明确,意思就是它应该表达的意思。

  • 或者,如果您愿意,可以使用 std::array<T, 5>作为:

    template <typename T> 
    inline T bigArry(const std::array<T,5> & data)

希望对您有所帮助。

关于c++ - 基于范围的循环和内联函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382383/

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