Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using c++11 auto as return type for const function object

I have a const function object and for the timebeing, it returnes void. but can return int or double. I am writing the code in c++11 style and was just trying to use auto as return type. Although the code compiles, I am not sure it is 100% correct or not. Here is the code.

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));

this code compiles and works in serial mode perfectly. Now I try to parallelize the above for_each using intel TBB parallel_for_each(). This requires the function object to be const. meaning the threads should not be allowed to modify or change the private variables of function object.

   //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

So I had to change the operator()() to the following:

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

   // do something

   } //operator

My question is: how do i use "auto operator()() ->void" and also make the operator "const" so that it becomes valid ?

like image 683
Pogo Avatar asked Oct 31 '22 22:10

Pogo


1 Answers

My question is: how do i use "auto operator()() ->void" and also make the operator "const" so that it becomes valid ?

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

     //do something with the edge.
   }

Remember, the declarator with a cv-qualifier has basically the following form:

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

(Omitted the attributes)

like image 101
Columbo Avatar answered Nov 15 '22 05:11

Columbo