在C ++中传递对数组的引用 [英] pass reference to array in C++

查看:146
本文介绍了在C ++中传递对数组的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助我理解以下代码



  #include< iostream& 

void foo(const char * c)
{
std :: cout< const char *< std :: endl;
}

template< size_t N>
void foo(const char(& t)[N])
{
std :: cout< array ref< std :: endl;
std :: cout<< sizeof(t)< std :: endl;
}

int main()
{
const char t [34] = {'1'};
foo(t);

char d [34] = {'1'};
foo(d);
}

输出为

  const char * 
数组ref
34


$ b b

为什么第一个foo调用 const char * 版本? c> const char [N] 转换 code>到 const char * 被认为是精确匹配(使文字更容易,主要是),在两个完全匹配之间,非模板函数优先。



您可以使用 enable_if is_array 强制






一个混乱的方式强制它可能是:

  #include< iostream> 

template< typename T>
void foo(const T * c)
{
std :: cout< const T *<< std :: endl;
}

template< typename T,size_t N>
void foo(const T(& t)[N])
{
std :: cout< array ref< std :: endl;
}

int main()
{
const char t [34] = {'1'};
foo(t)

char d [34] = {'1'};
foo(d);
}

/ *
数组ref
数组ref
* /

我意识到OP char 不是一些通用的 T 但是这表明问题在于一个重载是一个模板,而不是其他。


Can any one help me understand the following code

#include <iostream>

void foo(const char * c)
{
   std::cout << "const char *" << std::endl;
}

template <size_t N>
void foo(const char (&t) [N])
{
   std::cout << "array ref" << std::endl;
   std::cout << sizeof(t) << std::endl;
}

int main()
{
    const char t[34] = {'1'};
    foo(t);

    char d[34] = {'1'};
    foo(d);
}

The output is

const char *
array ref
34

Why does the first foo calls the const char * version ? How can I make it call the reference version ?

解决方案

Conversion of const char[N] to const char* is considered an "exact match" (to make literals easier, mainly), and between two exact matches a non-template function takes precedence.

You can use enable_if and is_array to force it to do what you want.


A messy way to force it might be:

#include <iostream>

template <typename T>
void foo(const T* c)
{
   std::cout << "const T*" << std::endl;
}

template <typename T, size_t N>
void foo(const T (&t) [N])
{
   std::cout << "array ref" << std::endl;
}

int main()
{
    const char t[34] = {'1'};
    foo(t);

    char d[34] = {'1'};
    foo(d);
}

/*
array ref
array ref
*/

I realise that the OP had char not some generic T, but nonetheless this demonstrates that the problem lay in one overload being a template and not the other.

这篇关于在C ++中传递对数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆