gpt4 book ai didi

使用 std::async 时的 C++ "Could not deduce template argument"

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:35 25 4
gpt4 key购买 nike

我对 C++ 和一般编程还很陌生。为了练习,我做了一个类似mergesort的排序算法。然后我尝试让它成为多线程。

std::future<T*> first = std::async(std::launch::async, &mergesort, temp1, temp1size);
std::future<T*> second = std::async(std::launch::async, &mergesort, temp2, temp2size);
temp1 = first.get();
temp2 = second.get();

但我的编译器似乎无法决定使用哪个模板,因为我两次遇到相同的错误。

Error   1   error C2783: 'std::future<result_of<enable_if<std::_Is_launch_type<_Fty>::value,_Fty>::type(_ArgTypes...)>::type> std::async(_Policy_type,_Fty &&,_ArgTypes &&...)' : could not deduce template argument for '_Fty'
Error 2 error C2784: 'std::future<result_of<enable_if<!std::_Is_launch_type<decay<_Ty>::type>::value,_Fty>::type(_ArgTypes...)>::type> std::async(_Fty &&,_ArgTypes &&...)' : could not deduce template argument for '_Fty &&' from 'std::launch'

这些错误让我相信 std::async 被两个不同的模板重载,一个用于指定的策略,一个用于未指定的策略,编译器无法选择正确的模板(我使用的是 Visual Studio Express 2013 ).那么如何向编译器指定合适的模板呢? (做 std::future<T*> second = std::async<std::launch::async>(&mergesort, temp2, temp2size); 似乎不起作用,我得到无效的模板参数,预期类型)。有没有更好的方法来一起完成这一切?谢谢!

最佳答案

您需要为mergesort 指定模板参数。异步不会足够聪明,无法自行解决。下面显示了一个基于迭代器的示例。它还利用当前事件线程作为递归点,而不是燃烧等待两个其他线程的线程句柄。

我警告你,有更好的方法可以做到这一点,但调整它可能会满足你的需求。

#include <iostream>
#include <algorithm>
#include <vector>
#include <thread>
#include <future>
#include <random>
#include <atomic>

static std::atomic_uint_fast64_t n_threads = ATOMIC_VAR_INIT(0);

template<typename Iter>
void mergesort(Iter begin, Iter end)
{
auto len = std::distance(begin,end);

if (len <= 16*1024) // 16K segments defer to std::sort
{
std::sort(begin,end);
return;
}

Iter mid = std::next(begin,len/2);

// start lower parttion async
auto ft = std::async(std::launch::async, mergesort<Iter>, begin, mid);
++n_threads;

// use this thread for the high-parition.
mergesort(mid, end);

// wait on results, then merge in-place
ft.wait();
std::inplace_merge(begin, mid, end);
}

int main()
{
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<> dist(1,100);

std::vector<int> data;
data.reserve(1024*1024*16);
std::generate_n(std::back_inserter(data), data.capacity(),
[&](){ return dist(rng); });

mergesort(data.begin(), data.end());
std::cout << "threads: " << n_threads << '\n';
}

输出

threads: 1023

您必须相信我,结束 vector 已排序。不会将 16MB 的值转储到此答案中。

注意:这是在 Mac 上使用 clang 3.3 编译和测试的,运行没有问题。不幸的是,我的 gcc 4.7.2 是脑死亡的,因为它在共享计数中止时抛出 cookie,但我对它所在的 libstdc++ 或 VM 没有很高的信心。

关于使用 std::async 时的 C++ "Could not deduce template argument",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22066542/

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