草庐IT

c++ - clang 中带有 std::async 的模板函数

coder 2024-02-05 原文

我正在查看 std::async 的示例 here ,如下:

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>

template <typename RAIter>
int parallel_sum(RAIter beg, RAIter end)
{
    auto len = std::distance(beg, end);
    if(len < 1000)
        return std::accumulate(beg, end, 0);

    RAIter mid = beg + len/2;
    auto handle = std::async(std::launch::async,
                              parallel_sum<RAIter>, mid, end);
    int sum = parallel_sum(beg, mid);
    return sum + handle.get();
}

int main()
{
    std::vector<int> v(10000, 1);
    std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
}

我尝试使用 Clang 3.4 的网络编译器对其进行编译,结果输出的是 The sum is 而不是预期的 The sum is 1000

我复制了示例并使用以下命令在 Ubuntu 14.04.1 64 位上使用 clang 3.5-1ubuntu1/gcc 4.8 进行了编译:

clang++ -g main.cpp -std=c++1y -o out -pthread;

我收到以下错误:

main.cpp:15:19: error: no matching function for call to 'async'

    auto handle = std::async(std::launch::async,
                  ^~~~~~~~~~
main.cpp:24:35: note: in instantiation of function template specialization
      'parallel_sum<__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> >
      > >' requested here
    std::cout << "The sum is " << parallel_sum(v.begin(), v.end()) << '\n';
                                  ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/future:1523:5: note: 
      candidate template ignored: substitution failure [with _Fn = int
      (__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >), _Args =
      <__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &>]:
      function cannot return function type 'int (__gnu_cxx::__normal_iterator<int *,
      std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int *,
      std::vector<int, std::allocator<int> > >)'
    async(launch __policy, _Fn&& __fn, _Args&&... __args)
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/future:1543:5: note: 
      candidate template ignored: substitution failure [with _Fn = std::launch, _Args = <int
      (__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >),
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &>]: no
      type named 'type' in 'std::result_of<std::launch (int
      (*)(__gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > >),
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &,
      __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int> > > &)>'
    async(_Fn&& __fn, _Args&&... __args)
    ^
1 error generated.
make: *** [all] Error 1

这是 clang、gcc、libstdc++ 中的错误,还是我遗漏了什么?

最佳答案

我认为这是 clang++ 中的一个错误。除非有一个我不知道的奇怪的限制规则,否则引用函数的 id 表达式是左值。但是,clang++ 在通用引用的推导中区分了函数模板特化和普通函数:

#include <iostream>

template<class T>
void print_type()
{
    std::cout << __PRETTY_FUNCTION__ << "\n";
}

template <class T>
int foo(bool) { return 42; }

int bar(bool) { return 42; }

template<class T>
void deduce(T&&)
{
    print_type<T>();
}

int main()
{
    deduce(foo<bool>);
    deduce(bar);
}

输出,clang++ 直到并包括早期的 3.5:

void print_type() [T = int (bool)]
void print_type() [T = int (&)(bool)]

Live example


std::result_of is used in libstdc++'s implementation of std::async to get the return type of the function (snippet from here):

template<typename _Fn, typename... _Args>
future<typename result_of<_Fn(_Args...)>::type>
async(launch __policy, _Fn&& __fn, _Args&&... __args)

如果我们通过 foo<bool>作为第二个参数,clang++ 推导出 _Fn == int (bool) .

函数(对象)的类型与 result_of 的参数类型相结合.这可能是 C++03 的遗留问题,那时我们还没有可变参数模板。传递参数类型以允许 result_of解决重载函数,如重载 operator()万一_Fn是一个类类型。

但是,如果 _Fn不是函数引用,而是函数类型,组合 _Fn(_Args...)形成非法类型:返回函数的函数:

     _Fn           == int(bool)
     _Args...      == bool
==>  _Fn(_Args...) == int(bool)(bool)

But there's more to it: The above declaration of async is defective, see LWG 2021. Howard Hinnant changed the declaration in libc++ to:

template <class F, class... Args>
future < typename result_of<
             typename decay<F>::type(typename decay<Args>::type...)
         >::type
       >
async(launch policy, F&& f, Args&&... args);

因此 libc++ 将函数衰减为函数指针。左值引用缺失导致的问题消失。

关于c++ - clang 中带有 std::async 的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25185595/

有关c++ - clang 中带有 std::async 的模板函数的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  5. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  9. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  10. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

随机推荐