gpt4 book ai didi

c++ - 如何初始化多种类型对象的自动类型数组

转载 作者:行者123 更新时间:2023-11-28 04:27:49 25 4
gpt4 key购买 nike

<分区>

我需要用 元组 的参数初始化一个数组。所以我试着这样设置:

auto average_intensity(Ts&&... args)
{
auto pixels[] = {args... };
// [...]
}

但是我得到以下错误:

‘pixels’ declared as array of ‘auto’ auto pixels[] = {args... };

我该如何解决这个问题?

完整代码如下:

#include <iostream>
#include <type_traits>
#include <string>
#include <utility>
#include <tuple>


using namespace std;

struct gray_pixel{
uint8_t gray;
auto intensity(){
return gray - 127;
}
};


struct rgb_pixel{
float red, green, blue;
auto intensity(){
return (red - 127 + green -127 + blue - 127) * 255 / 3;
}
};


template<typename T>
auto intensity(T pixel){
return pixel.intensity();
}
//find the average intensity of multiple pixels from different types (gray_pixel or rgb_pixel)
template <typename... Ts>
auto average_intensity(Ts&&... args)
{
auto pixels[] = {args...};

auto sum = 0;
int count = 0;
for(auto pixel : pixels){
sum +=intensity(pixel);
count++;
}
return sum/count;
}


int main()
{

gray_pixel pixel_gray = {255};
rgb_pixel pixel_rgb = {0,0,250};

cout << "sizeof(pixel_gray): " << sizeof(pixel_gray) << endl;
cout << "sizeof(pixel_rgb): " << sizeof(pixel_rgb) << endl;

cout << "intensity(pixel_gray): " << intensity(pixel_gray) << endl;
cout << "intensity(pixel_rgb): " << intensity(pixel_rgb) << endl;

cout << "average_intensity(pixel_gray, pixel_rgb): " << average_intensity(pixel_gray, pixel_rgb) << endl;
return 0;
}

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