我想知道如何实现以下设计。我没有努力遵循标准惯例,以便将这个虚拟代码保持在最低限度(例如,包括警卫)。为了论证,我使用的是C ++ 03,只使用标准库组件。
TL; DR :我的Restaurant
和Recipe
类之间存在循环依赖关系。我在std::set<>
类中有Recipe
对象的Restaurant
个#include
,反之亦然。我不能value_type
一个在另一个,但由于前向声明,编译器不允许我为集合声明自定义比较器,因为此时/*
* restaurant.h
*/
#include <string>
#include <set>
/*
* I cannot do this as recipe.h would need to include
* restaurant.h, which restricts
* me when I want to write a custom comparator.
*/
// #include "recipe.h"
class Recipe;
// I know this will not work as Recipe has not yet been declared.
struct RecipeComparator {
bool operator() (const Recipe* lhs, const Recipe* rhs) {
return lhs->price() < rhs->price();
}
};
class Restaurant {
public:
Restaurant(const std::string& name, float averagePrice);
float averagePrice() { return m_averagePrice; }
private:
std::string m_name;
float m_averagePrice;
/*
* I want to have the recipies sorted by their prices.
* I cannot define RecipeComparator here as Restaurant
* is an incomplete type till now.
*/
std::set< Recipe*, RecipeComparator > m_recipiesSorted;
/*
* This works, but does not do what I want.
*/
std::set< Recipe* > m_recipies;
};
仍然是不完整的类型。有没有办法实现这个目标?
我在代码中添加了注释,可以更详细地解释我的问题。
/*
* recipe.h
*/
#include <string>
#include <set>
/*
* I cannot do this as restaurant.h would need to include
* recipe.h, so I need to forward declare, which restricts
* me when I want to write a custom comparator.
*/
// #include "restaurant.h"
class Restaurant;
// I know this will not work as Restaurant has not yet been declared.
struct RestaurantComparator {
bool operator() (const Restaurant* lhs, const Restaurant* rhs) {
return lhs->averagePrice() < rhs->averagePrice();
}
};
class Recipe {
public:
Recipe(const std::string& name, float price);
float price() { return m_price; }
private:
std::string m_name;
float m_price;
/*
* This is what I want as I want to have the restaurants sorted
* by their average prices.
* I cannot define RestaurantComparator here as Restaurant
* is an incomplete type till now.
*/
std::set< Restaurant*, RestaurantComparator > m_restaurantsSorted;
/*
* This works, but does not do what I want.
*/
std::set< Restaurant* > m_restaurants;
};
{{1}}
答案 0 :(得分:4)
一个想法是将Comparator定义移动到.cpp源,同时保持标头中的声明。这样,restaurant.h
和recipe.h
仍然只会通过名称互相引用,因此前向声明仍然足够。
// restaurant_recipe_comparators.h
// probably too long, give it a better name
struct RestaurantComparator
{
bool operator() (const Restaurant *, const Restaurant *);
};
struct RecipeComparator
{
bool operator() (const Recipe *, const Recipe *);
};
// restaurant_recipe_comparators.cpp
bool RestaurantComparator::operator() (const Restaurant* lhs, const Restaurant* rhs)
{
return lhs->averagePrice() < rhs->averagePrice();
}
bool RecipeComparator::operator() (const Recipe* lhs, const Recipe* rhs)
{
return lhs->price() < rhs->price();
}