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

标签 c++ loops c++11 inline

我这里有这段代码。

#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/

相关文章:

Javascript:for循环获取数据但顺序被破坏

c++ - memmove 和 c++11 std::move 有什么区别?

c++ - 如何在 Mac 上使用 IDE(intelJ 或 Xcode)高效调试 tensorflow 内部 C++ 代码?

C 延迟无限循环中奇怪的 kbhit() 行为

loops - Tcl foreach 循环中的 awk 命令

c++ - 为什么 std::condition_variable 不是按锁类型模板化的?

c++ - libstdc++ 是否实现 C++11 双端队列接口(interface)?

c++ - QLabel在调整大小时切断文本

c++ - 快速排序(n 个数组应被视为 1 并根据需要重新映射值)

c++ - OpenGL 中的阴影贴图