是否可以在内部使用const
编写apply_visitor
函数?
例如,此代码编译没有错误:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <boost/variant.hpp>
using namespace std;
typedef boost::variant<int,string> vTypeVariants;
struct vType_toN : boost::static_visitor<int>
{
int operator()(int& i) const {
return i;
}
int operator()(const string& str) const{
return str.length();
}
};
class vType{
public:
vType(const int& src) : data(src){}
vType(const std::string& src) : data(src){}
int getLength(){
return boost::apply_visitor(vType_toN(),data);
}
private:
vTypeVariants data;
};
int main(int argc, char ** argv)
{
vType x = string("2");
printf("L=%d",x.getLength());
return(0);
}
除非您将const添加到getLength():
int getLength() const{
return boost::apply_visitor(vType_toN(),data);
}
在这种情况下,出现大量描述错误(共2页),抱怨初始化第一个参数存在问题。
所以,问题是:如何在const函数内使用apply_visitor?
最佳答案
发现自己。
在static_visitor类运算符定义中,在int之前忘记了const。
也许有人会觉得这很有用,因为要找到它并不容易(我的原始班级要大得多)。
关于c++ - 如何使申请访客不丢弃const限定词?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19896046/