【发布时间】: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 -> void -
您不必必须使用尾随返回类型,因为您可以!
-
你为什么要写
auto foo() -> void?试图赢得混淆比赛?还是让同事打你的脸?
标签: c++ c++11 tbb boost-graph