我有以下代码:
struct STFRandomTreeFunction { typedef double(* function_ptr)(const STFDataPoint& data,boost :: unordered_map& preloaded_images); };
struct STFRandomTreeFunctor
{
private:
boost::unordered_map<std::string, cv::Mat> *image_cache;
STFRandomTreeFunction::function_ptr function;
std::string function_id;
public:
STFRandomTreeFunctor(boost::unordered_map<std::string, cv::Mat>& cache, STFRandomTreeFunction::function_ptr function, std::string function_id)
:image_cache(&cache), function(function), function_id(function_id){}
std::string get_function_id(){
return function_id;
}
double operator()(const TrainingDataPoint& data_point){
return function(data_point, *image_cache);
}
};
unordered_map<string, STFRandomTreeFunctor> lut;
double a(const STFDataPoint& b, unordered_map<string, Mat>& c){
return 5;
}
int main(int argc, char* argv[]) {
unordered_map<string, Mat> cache;
lut["a"] = STFRandomTreeFunctor(cache, a, "a");
}
当我尝试构建时,我收到以下错误:boost/unordered/detail/allocate.hpp:262:1: error: no matching function for call to ‘STFRandomTreeFunctor::STFRandomTreeFunctor()’
但是我不知道为什么boost试图调用STFRandomTreeFunctor()
,这是因为当我们创建空映射时,它会尝试创建一个STFRandomTreeFunctor吗?如果是这样,我该如何解决这个问题?
由于
答案 0 :(得分:1)
电话
lut["a"] = x;
将首先在themap
中创建一个空条目(cfr。operator[]:“效果:
如果容器尚未包含具有等于k的键的元素,则插入值std::pair<key_type const, mapped_type>(k, mapped_type())
“)。要构造mapped_type()
,它需要一个默认构造函数。
如果您想避免这种情况,请使用insert
功能:
bool inserted=lut.insert( std::make_pair("a",x) ).second;
assert(inserted); // unless it's ok to not overwrite already inserted keys
但是这样,你需要一个复制构造函数(或move-constructor),因为新创建的pair
将被复制到地图中。
答案 1 :(得分:1)
当你在main函数中使用lut["a"]
时,map应该返回对类型为STFRandomTreeFunctor
的初始化值的引用,如你所见,它没有参数来创建和初始化该实例,所以它使用类的默认构造函数,您的类没有默认构造函数。所以您应该为您的类编写默认构造函数或使用:
lut.insert( std::make_pair("a", STFRandomTreeFunctor(cache, a, "a")) );
答案 2 :(得分:0)
将结构定义放在首位,基本上它正在尝试构造unordered_map<string, STFRandomTreeFunctor> lut;
,但找不到结构的定义:)
struct STFRandomTreeFunction
{
typedef double (*function_ptr)(const STFDataPoint& data, boost::unordered_map<std::string, cv::Mat>& preloaded_images);
};
struct STFRandomTreeFunctor
{
private:
boost::unordered_map<std::string, cv::Mat> *image_cache;
STFRandomTreeFunction::function_ptr function;
std::string function_id;
public:
STFRandomTreeFunctor(boost::unordered_map<std::string, cv::Mat>& cache, STFRandomTreeFunction::function_ptr function, std::string function_id)
:image_cache(&cache), function(function), function_id(function_id){}
std::string get_function_id(){
return function_id;
}
double operator()(const TrainingDataPoint& data_point){
return function(data_point, *image_cache);
}
};
unordered_map<string, STFRandomTreeFunctor> lut;
double a(const STFDataPoint& b, unordered_map<string, Mat>& c){
return 5;
}
int main(int argc, char* argv[]) {
unordered_map<string, Mat> cache;
lut["a"] = STFRandomTreeFunctor(cache, a, "a");
}