【问题标题】:using c++11 auto as return type for const function object使用 c++11 auto 作为 const 函数对象的返回类型
【发布时间】:2014-06-02 22:44:13
【问题描述】:

我有一个 const 函数对象,暂时它返回 void。但可以返回 int 或 double。我正在用 c++11 风格编写代码,只是试图使用 auto 作为返回类型。尽管代码可以编译,但我不确定它是否 100% 正确。这是代码。

template <typename graph_t>
 struct my_func { 
   public:
    my_func() {  } 
    my_func (graph_t&  _G) : G(_G) {  } 

   template <typename edge_t>
   auto operator()(edge_t   edge) -> void const {

     //do something with the edge.
   } //operator

   private:
    graph_t& G;
   };

   //call the functor: (pass graph G as template parameter)
   std::for_each(beginEdge, endEdge, my_func<Graph>(G));

此代码完美地编译并在串行模式下工作。现在我尝试使用 intel TBB parallel_for_each() 并行化上述 for_each。这要求函数对象为 const。这意味着不应允许线程修改或更改函数对象的私有变量。

   //tbb::parallel_for_each
   tbb::paralle_for_each(beginEdge, endEdge, my_func<Graph>(G));

   Now, the compiler error comes: 
   passing const my_func< ... > ..  discards qualifiers

所以我不得不将 operator()() 更改为以下内容:

   template <typename edge_t>
   void operator()(edge_t  edge) const { 

   // do something

   } //operator

我的问题是:我如何使用“auto operator()() ->void”并让运算符“const”变得有效?

【问题讨论】:

  • 把“const”放在箭头前面?
  • auto operator()(edge_t edge) const -&gt; void
  • 您不必必须使用尾随返回类型,因为您可以
  • 你为什么要写auto foo() -&gt; void?试图赢得混淆比赛?还是让同事打你的脸?

标签: c++ c++11 tbb boost-graph


【解决方案1】:

我的问题是:我如何使用“auto operator()() ->void”并且还使 运算符 "const" 使其变为有效?

   template <typename edge_t>
   auto operator()(edge_t   edge) const -> void
   {

     //do something with the edge.
   }

请记住,带有 cv 限定符的声明符基本上具有以下形式:

( parameter-declaration-clause ) cv-qualifier-seq [ref-qualifier] [exception-specification] [trailing-return-type]

(省略属性)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多