gpt4 book ai didi

c++ - 设置一个 C 风格的数组,模板函数接受回调

转载 作者:行者123 更新时间:2023-11-30 00:43:52 28 4
gpt4 key购买 nike

那么,假设我正在编写一个函数来使用用户提供的每个项目的回调来设置一个数组。 (我不是,但为了最小示例的目的,假设我是)

我能找到的最干净的方法如下:

#include <functional>

template<typename T, typename Y>
void PopulateArray(std::function<int(Y*)> callback, T &pArray)
{
for (int i = 0; i < sizeof(pArray); ++i)
int x = callback(&pArray[i]);
}

int main()
{
uint64_t myArray[5];
uint64_t myUint = 42;
PopulateArray( (std::function<int(uint64_t*)>) [=](auto x) {*x = myUint; return 0; },
myArray);
}

上面的代码有两个问题。

1)T是数组类型,好像没办法修改参数。 (我不能说我想要一个 T 类型的 array,这意味着我必须单独声明 Y,即使它们都与uint64_t。)我宁愿声明单个 T,其中一个参数是指向 T 的指针,另一个是 的数组>T

2) 客户端代码(在 main 中)被迫转换 lambda。将 auto x 更改为显式类型似乎无济于事。

#1 或#2 是否有可能使代码更简洁或可读性更好的解决方案?

代码需要使用 gcc、clang 和 VS 进行编译。我认为 C++11 是我可以使用的最新标准,尽管我对 C++14 解决方案感兴趣,因为那将是升级我们的 clang 构建过程的问题。我对涉及将 myArray 切换为 std::array std::vector 等的解决方案不感兴趣。

最佳答案

删除 std::function 的要求:

// You could consider using an array type for the parameter:
// template <typename Callback, typename T, std::size_t N>
// void PopulateArray(Callback callback, T (&pArray)[N])
template<typename Callback, typename T>
void PopulateArray(Callback callback, T& pArray)
{
// sizeof(pArray) as in the question is almost certainly not what you
// want. It returns the size *in bytes*, not the length of the array.
// Thus, if you specified this to take an array reference,
// `for (std::size_t i = 0; i < N; ++i)` would be correct.

// However, as Barry mentioned in the comments, a range-based for loop
// is the best solution.
for (T& element : pArray)
callback(&element);
}

int main()
{
std::uint64_t myArray[5];
PopulateArray([](auto x) {*x = 42; return 0; },
myArray);
}

std::function 是一种昂贵的类型。它使用虚函数调用(或非常相似的技术)并具有分配内存的潜力。如果您不存储该函数,特别是如果该函数已经是一个模板,则只需将任意回调作为您的参数。如果您真的想限制回调的类型,请使用 function_ref 类型(尚未标准化),或检查 callback(your, args) 是否有效:

template<typename Callback, typename T>
auto PopulateArray(Callback callback, T& pArray)
-> decltype(callback(*std::begin(pArray)), void())
{
for (T& element : pArray)
callback(&element);
}

此外,在这种特定情况下,您可以使用 an algorithm :

int main()
{
uint64_t myArray[5];
uint64_t myUint = 42;
// If it's all the same value:
std::fill(std::begin(myArray), std::end(myArray), myUint);
// To call a function to populate the array:
std::generate(std::begin(myArray), std::end(myArray), [myUint] {
return myUint;
});
// Or possibly:
std::for_each(std::begin(myArray), std::end(myArray),
[myUint](uint64_t& element) {
element = myUint;
});
}

关于c++ - 设置一个 C 风格的数组,模板函数接受回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066922/

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