簡體   English   中英

使用std :: async時,C ++“無法推斷出模板參數”

[英]C++ “Could not deduce template argument” when using std::async

一般來說,我對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

您必須相信我,最終向量已排序。 不會將16MB的值轉儲到此答案中。

注意:此文件在Mac上使用clang 3.3進行了編譯和測試,並且沒有問題。 不幸的是,我的gcc 4.7.2死了,因為它會在共享計數中止時拋出cookie,但是我對它所在的libstdc ++或VM並不抱有很高的信心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM