【问题标题】:How to pass array to function template with reference如何通过引用将数组传递给函数模板
【发布时间】:2013-05-12 08:06:45
【问题描述】:

我正在学习 C++ 模板概念。我不明白以下内容。

#include <iostream>
#include <typeinfo>

using namespace std;

template <typename T>
T fun(T& x)
{
 cout <<" X is "<<x;
 cout <<"Type id is "<<typeid(x).name()<<endl;
}


int main ( int argc, char ** argv)
{
   int a[100];
   fun (a);
}

我在尝试什么?

1) 有趣(T & x)

这里的 x 是一个引用,因此不会将 'a' 衰减为指针类型, 但是在编译时,我收到以下错误。

 error: no matching function for call to ‘fun(int [100])’

当我尝试非参考时,它工作正常。据我了解,数组已衰减为指针类型。

【问题讨论】:

    标签: c++


    【解决方案1】:

    C 风格的数组是非常基本的结构,不能像内置或用户定义的类型那样分配、复制或引用。要实现通过引用传递数组的等价,您需要以下语法:

    // non-const version
    template <typename T, size_t N>
    void fun( T (&x)[N] ) { ... }
    
    // const version
    template <typename T, size_t N>
    void fun( const T (&x)[N] ) { ... }
    

    请注意,这里数组的大小也是一个模板参数,以允许函数对所有数组大小起作用,因为T[M]T[N] 对于不同的MN 的类型不同。另请注意,该函数返回 void。无法按值返回数组,因为数组不可复制,如前所述。

    【讨论】:

    • rodrigo的回答也是正确的,不用引入额外的N,(T&x)也可以捕捉到T类型为“int [100]”的“int a[100]”,甚至可以声明局部变量使用 T: {T t; t[999]=1;}
    • @TingQianLI 是的,确实。这取决于预期的用途。此版本的可能优点是它仅适用于数组,并且模板参数N 具有数组的长度。
    【解决方案2】:

    问题在于返回类型:你不能返回一个数组,因为数组是不可复制的。顺便说一句,你什么都没有返回!

    试试吧:

    template <typename T>
    void fun(T& x)  // <--- note the void
    {
        cout <<" X is "<<x;
        cout <<"Type id is "<<typeid(x).name()<<endl;
    }
    

    它会按预期工作。

    注意:原始的完整错误消息(使用 gcc 4.8)实际上是:

    test.cpp: In function ‘int main(int, char**)’:
    test.cpp:17:10: error: no matching function for call to ‘fun(int [100])’
        fun (a);
          ^
    test.cpp:17:10: note: candidate is:
    test.cpp:7:3: note: template<class T> T fun(T&)
     T fun(T& x)
       ^
    test.cpp:7:3: note:   template argument deduction/substitution failed:
    test.cpp: In substitution of ‘template<class T> T fun(T&) [with T = int [100]]’:
    test.cpp:17:10:   required from here
    test.cpp:7:3: error: function returning an array
    

    最相关的行是最后一行。

    【讨论】:

    • “有效的现代 c++”中的第 1 项也暗示了这种方式。写(&amp;param)[N] 是多余的,除非你需要在f 的正文中引用N(尽管一旦你有了类型也可以推断出来)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多