C++ 变量访问者返回错误(最烦人的解析?)
我有一个C++ 变量访问者返回错误(最烦人的解析?),c++,c++11,gcc,boost,boost-variant,C++,C++11,Gcc,Boost,Boost Variant,我有一个std::arrayofboost::variant对象,我试图创建一个boost::static\u visitor,它访问数组中的一个元素,返回对每个variant成员类型中某些内容的引用。这是一个很好的例子,下面是一个模仿我的实现的代码片段: #include <boost/variant.hpp> #include <array> struct SomeType {}; struct A { SomeType something; SomeTy
std::array
ofboost::variant
对象,我试图创建一个boost::static\u visitor
,它访问数组中的一个元素,返回对每个variant成员类型中某些内容的引用。这是一个很好的例子,下面是一个模仿我的实现的代码片段:
#include <boost/variant.hpp>
#include <array>
struct SomeType {};
struct A {
SomeType something;
SomeType& someMethod() { return something; }
};
struct B {
SomeType something;
SomeType& someMethod() { return something; }
};
struct C {
SomeType something;
SomeType& someMethod() { return something; }
};
typedef boost::variant<A, B, C> MyVariant;
class SomeVisitor : public boost::static_visitor<> {
public:
template<typename T>
SomeType& operator()(T& operand) const {
return operand.someMethod();
}
};
class MyVariants {
public:
SomeType* getSomething(unsigned index);
private:
static const size_t count = 100;
std::array<MyVariant, count> variants_;
};
SomeType* MyVariants::getSomething(unsigned index) {
if(index < count) {
MyVariant& variant = variants_[index];
SomeType& something = boost::apply_visitor(SomeVisitor(), variant);
return &something;
}
else {
return nullptr;
}
}
在这种情况下,我可以理解最麻烦的解析是如何应用的<代码>MyVariant(A())代码>可能对编译器不明确。但我不知道这是如何应用于我的代码段的,因为MyVariant&variant=variants\uu[index]
似乎非常明确。我不知道这些问题是否与我的问题有关
任何建议/帮助都将不胜感激作为回答提供的评论:
您必须在static_访问者的模板参数列表中指定返回类型。将其保留为空表示告知编译器函子将返回void
class SomeVisitor : public boost::static_visitor<SomeType&> {
public:
template<typename T>
SomeType& operator()(T& operand) const {
return operand.someMethod();
}
};
您必须在static_访问者的模板参数列表中指定返回类型。保留为空表示告诉编译器函子将返回void。谢谢!这正是问题所在。几周前,我做了一个带有返回值的
boost::static\u visitor
(语法正确),所以我倍感尴尬,因为我们都这么做了。请注意,在使用c++14的更高版本的boost中,您不需要静态访问者。参数类型为auto&
的lambda就足够了。
MyVariant variant(A());
SomeType& something = boost::apply_visitor(SomeVisitor(), variant);
class SomeVisitor : public boost::static_visitor<SomeType&> {
public:
template<typename T>
SomeType& operator()(T& operand) const {
return operand.someMethod();
}
};
auto& something = boost::apply_visitor([](auto& x) { return x.someMethod(); },
variant);