我们可以通过下面的语法传递数组作为函数的参数,在即将到来的C ++ 0x标准呢? [英] can we pass arrays as arguments to functions by this syntax, under upcoming c++0x standards?

查看:170
本文介绍了我们可以通过下面的语法传递数组作为函数的参数,在即将到来的C ++ 0x标准呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下功能:

void someFunction(int * araye){
 for (int i=0;i<5;i++)
  cout <<araye[i]<<' ';
 cout <<'\n';
}

我们可以通过下面的语法传递一个数组到这个功能,在即将到来的C ++ 0x标准呢?

can we pass an array to this function by following syntax, under upcoming c++0x standards? :

someFunction({1,2,3,4,5});

如果这是真的,我们会甚至能够在任何情况下使用此语法中,数组元素是从POD类型象下面这样:

if that's true, will we even be able to use this syntax in any case in which, array elements are from POD types like below :

class Test{
 int adad1;
 int adad2;
};
void someFunction(Test * araye){
 for (int i=0;i<3;i++)
  cout <<araye[i].adad1<<'-'<<araye[i].adad2<<' ';
 cout <<'\n';
}
someFunction({{1,2},{3,4},{5,6}});

编辑 - >后是什么人说:结果
所以你们在告诉括号之间的前pression将作为一个initializer_list可基本处理,并使用该翻出一个指针出initializer_list,并把它传递给预定功能的额外功能的建议,但这种方法在我看来,像一个黑客才能够使用我的预期功能与前pression作为参数,随着中说,我认为我不应该使用前pression作为参数可言,当我的预期功能参数一个指针,或者有可能是使用前pression另一种方法?

Edit->after what people said:
So you guys are telling that the expression between braces will be basically treated as an initializer_list and are proposing using an extra function that pulls a pointer out of that initializer_list and passes it to the intended function, but this method seems to me like a hack to be able to use my intended function with that expression as an argument, with that said I think I shouldn't use that expression as an argument at all, when my intended function parameter is a single pointer, or there might be another approach to use that expression? .

推荐答案

如果您的函数有 const int的* ,而不是为int * ,那么你只需要一个小蹦床功能拉指针移出的std :: initializer_list&LT; INT&GT; 的括号初始化器产生。像这样的东西(可能是,我没有的C ++ 0x编译器进行测试)

If your function takes const int*, rather than int*, then you just need a small trampoline function to pull the pointer out of the std::initializer_list<int> that the brace initialiser produces. Something like this (probably; I don't have a C++0x compiler to test with)

void someFunction(const int * array){
    for (int i=0; i<5; i++)
        std::cout << array[i] << ' ';
    std::cout << '\n';
}

void someFunction(const std::initializer_list<int>& init) {
    someFunction(init.begin());
}

someFunction({1,2,3,4,5});

如果你的函数需要知道数组的结尾或大小(通常会是这样),那么通过其中 init.end() init.size()作为第二个参数。

If your function needs to know the end or size of the array (which will usually be the case), then pass either init.end() or init.size() as a second argument.

这篇关于我们可以通过下面的语法传递数组作为函数的参数,在即将到来的C ++ 0x标准呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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