我有一个对象“标识符”列表(一个很长的枚举列表,每个“标识符”都有一个唯一值):
enum Identifier {
Enum0, // an identifier for a bool value
Enum1, // ... for a float value
Enum2, // ... for an int value
// etc.
};
我希望维护与这些标识符关联的值对象的集合。这些 Value 对象包含单个值,但该值可以是整数、 float 、 bool 值或其他(简单)类型。这是在管理系统中的一组配置值的上下文中。稍后我计划扩展这些值类型以支持内部值的验证,并将一些值与其他值相关联。
但是我希望为这些值类使用模板,因为我想对这些值进行通用的操作。如果我要使用继承,我将拥有 BaseValue,然后从 BaseValue 派生 IntValue、FloatValue 等。相反,我有 Value、Value 等。
但我还想在单个集合中存储对这些值中的每一个的访问机制。我想要一个类来实例化所有这些并将它们维护在集合中。如果我使用继承,我可以使用指向 BaseValue 的指针 vector 。但是因为我使用的是模板,所以这些类彼此之间没有多态相关。
所以我考虑让它们基于一个未参数化的(空的?)抽象基类:
class BaseParameter {
};
template<typename T>
class Parameter : public BaseParameter {
public:
explicit Parameter(T val) : val_(val) {}
void set(ParameterSource src) { val_ = extract<T>(src); }
T get() { return val_; };
private:
T val_;
};
请注意,“set”成员函数采用“ParameterSource”,这是由特定“to_type”函数“重新解释”的值的来源。这是一个我无法控制的 API 函数——我必须自己解释类型,因为我知道类型的含义,如下所示。这就是 extract 的作用 - 它专用于各种 T 类型,如 float、int、bool。
然后我可以像这样将它们添加到 std::vector 中:
std::vector<BaseParameter *> vec(10);
vec[Enum0] = new Parameter<bool>(true); // this is where I state that it's a 'bool'
vec[Enum1] = new Parameter<float>(0.5); // ... or a float ...
vec[Enum2] = new Parameter<int>(42); // ... or an int ...
我知道我可能应该使用 unique_ptr 但现在我只是想让它正常工作。到目前为止,这似乎工作正常。但我对此持谨慎态度,因为我不确定实例化模板的完整类型是否会在运行时保留。
稍后我想通过任意枚举值索引“vec”,检索参数并在其上调用成员函数:
void set_via_source(Identifier id, ParameterSource source) {
// if id is in range...
vec[id]->set(source);
}
其他使用这些配置值(因此知道类型)的代码可以通过以下方式访问它们:
int foo = vec[Enum2]->get() * 7;
这似乎在大多数时候都有效。它编译。我遇到了一些我无法解释的奇怪崩溃,它们也往往会使调试器崩溃。但我对此非常怀疑,因为我不知道 C++ 是否能够确定指向对象的真实类型(包括参数化类型),因为基类本身没有参数化。
不幸的是,在我看来,如果我对基类进行参数化,那么我基本上消除了这些允许它们存储在单个容器中的值类之间的共性。
我查看了 boost::any 看是否有帮助,但我不确定它是否适用于这种情况。
在更高的层次上,我正在尝试做的是连接来自外部源(通过 API)的大量配置项,这些配置项根据项目提供不同类型的值,并将它们存储在本地,以便我的其余代码可以轻松访问它们,就好像它们是简单的数据成员一样。我也想避免编写一个巨大的 switch 语句(因为那会起作用)。
Type Erasure 可以帮我解决这个问题吗?
最佳答案
如果您在编译时知道与每个枚举关联的类型,则可以使用 boost::variant
“轻松”地完成此操作,而无需类型删除甚至继承。 (编辑:第一个解决方案使用了大量 C++11 功能。我在最后放置了一个自动化程度较低但符合 C++03 的解决方案。)
#include <string>
#include <vector>
#include <boost/variant.hpp>
#include <boost/variant/get.hpp>
// Here's how you define your enums, and what they represent:
enum class ParameterId {
is_elephant = 0,
caloric_intake,
legs,
name,
// ...
count_
};
template<ParameterId> struct ConfigTraits;
// Definition of type of each enum
template<> struct ConfigTraits<ParameterId::is_elephant> {
using type = bool;
};
template<> struct ConfigTraits<ParameterId::caloric_intake> {
using type = double;
};
template<> struct ConfigTraits<ParameterId::legs> {
using type = int;
};
template<> struct ConfigTraits<ParameterId::name> {
using type = std::string;
};
// ...
// Here's the stuff that makes it work.
class Parameters {
private:
// Quick and dirty uniquifier, just to show that it's possible
template<typename...T> struct TypeList {
using variant = boost::variant<T...>;
};
template<typename TL, typename T> struct TypeListHas;
template<typename Head, typename...Rest, typename T>
struct TypeListHas<TypeList<Head, Rest...>, T>
: TypeListHas<TypeList<Rest...>, T> {
};
template<typename Head, typename...Rest>
struct TypeListHas<TypeList<Head, Rest...>, Head> {
static const bool value = true;
};
template<typename T> struct TypeListHas<TypeList<>, T> {
static const bool value = false;
};
template<typename TL, typename T, bool B> struct TypeListMaybeAdd;
template<typename TL, typename T> struct TypeListMaybeAdd<TL, T, false> {
using type = TL;
};
template<typename...Ts, typename T>
struct TypeListMaybeAdd<TypeList<Ts...>, T, true> {
using type = TypeList<Ts..., T>;
};
template<typename TL, typename T> struct TypeListAdd
: TypeListMaybeAdd<TL, T, !TypeListHas<TL, T>::value> {
};
template<typename TL, int I> struct CollectTypes
: CollectTypes<typename TypeListAdd<TL,
typename ConfigTraits<ParameterId(I)>::type
>::type, I - 1> {
};
template<typename TL> struct CollectTypes<TL, 0> {
using type = typename TypeListAdd<TL,
typename ConfigTraits<ParameterId(0)>::type
>::type::variant;
};
public:
using value_type =
typename CollectTypes<TypeList<>, int(ParameterId::count_) - 1>::type;
template<ParameterId pid>
using param_type = typename ConfigTraits<pid>::type;
// It would be better to not initialize all the values twice, but this
// was easier.
Parameters() : values_(size_t(ParameterId::count_)) {
clear(std::integral_constant<int, int(ParameterId::count_) - 1>());
}
// getter for when you know the id at compile time. Should have better
// error checking.
template<ParameterId pid>
typename ConfigTraits<pid>::type get() {
// The following will segfault if the value has the wrong type.
return *boost::get<typename ConfigTraits<pid>::type>(&values_[int(pid)]);
}
// setter when you know the id at compile time
template<ParameterId pid>
void set(typename ConfigTraits<pid>::type new_val) {
values_[int(pid)] = new_val;
}
// getter for an id known only at runtime; returns a boost::variant;
value_type get(ParameterId pid) {
return values_[int(pid)];
}
private:
// Initialize parameters to default values of the correct type
template<int I> void clear(std::integral_constant<int, I>) {
values_[I] = param_type<ParameterId(I)>();
clear(std::integral_constant<int, I - 1>());
}
void clear(std::integral_constant<int, 0>) {
values_[0] = param_type<ParameterId(0)>();
}
std::vector<value_type> values_;
};
// And finally, a little test
#include <iostream>
int main() {
Parameters parms;
std::cout << ('(' + parms.get<ParameterId::name>() + ')')<< ' '
<< parms.get<ParameterId::is_elephant>() << ' '
<< parms.get<ParameterId::caloric_intake>() << ' '
<< parms.get<ParameterId::legs>() << std::endl;
parms.set<ParameterId::is_elephant>(true);
parms.set<ParameterId::caloric_intake>(27183.25);
parms.set<ParameterId::legs>(4);
parms.set<ParameterId::name>("jumbo");
std::cout << ('(' + parms.get<ParameterId::name>() + ')')<< ' '
<< parms.get<ParameterId::is_elephant>() << ' '
<< parms.get<ParameterId::caloric_intake>() << ' '
<< parms.get<ParameterId::legs>() << std::endl;
return 0;
}
为了那些还不能使用 C++11 的人的利益,这里有一个使用非类枚举的版本,它不够聪明,无法通过以下方式构建 boost::variant
类型本身,所以你必须手动提供它:
#include <string>
#include <vector>
#include <boost/variant.hpp>
#include <boost/variant/get.hpp>
// Here's how you define your enums, and what they represent:
struct ParameterId {
enum Id {
is_elephant = 0,
caloric_intake,
legs,
name,
// ...
count_
};
};
template<int> struct ConfigTraits;
// Definition of type of each enum
template<> struct ConfigTraits<ParameterId::is_elephant> {
typedef bool type;
};
template<> struct ConfigTraits<ParameterId::caloric_intake> {
typedef double type;
};
template<> struct ConfigTraits<ParameterId::legs> {
typedef int type;
};
template<> struct ConfigTraits<ParameterId::name> {
typedef std::string type;
};
// ...
// Here's the stuff that makes it work.
// C++03 doesn't have integral_constant, so we need to roll our own:
template<int I> struct IntegralConstant { static const int value = I; };
template<typename VARIANT>
class Parameters {
public:
typedef VARIANT value_type;
// It would be better to not initialize all the values twice, but this
// was easier.
Parameters() : values_(size_t(ParameterId::count_)) {
clear(IntegralConstant<int(ParameterId::count_) - 1>());
}
// getter for when you know the id at compile time. Should have better
// error checking.
template<ParameterId::Id pid>
typename ConfigTraits<pid>::type get() {
// The following will segfault if the value has the wrong type.
return *boost::get<typename ConfigTraits<pid>::type>(&values_[int(pid)]);
}
// setter when you know the id at compile time
template<ParameterId::Id pid>
void set(typename ConfigTraits<pid>::type new_val) {
values_[int(pid)] = new_val;
}
// getter for an id known only at runtime; returns a boost::variant;
value_type get(ParameterId::Id pid) {
return values_[int(pid)];
}
private:
// Initialize parameters to default values of the correct type
template<int I> void clear(IntegralConstant<I>) {
values_[I] = typename ConfigTraits<I>::type();
clear(IntegralConstant<I - 1>());
}
void clear(IntegralConstant<0>) {
values_[0] = typename ConfigTraits<0>::type();
}
std::vector<value_type> values_;
};
// And finally, a little test
#include <iostream>
int main() {
Parameters<boost::variant<bool, int, double, std::string> > parms;
std::cout << ('(' + parms.get<ParameterId::name>() + ')')<< ' '
<< parms.get<ParameterId::is_elephant>() << ' '
<< parms.get<ParameterId::caloric_intake>() << ' '
<< parms.get<ParameterId::legs>() << std::endl;
parms.set<ParameterId::is_elephant>(true);
parms.set<ParameterId::caloric_intake>(27183.25);
parms.set<ParameterId::legs>(4);
parms.set<ParameterId::name>("jumbo");
std::cout << ('(' + parms.get<ParameterId::name>() + ')')<< ' '
<< parms.get<ParameterId::is_elephant>() << ' '
<< parms.get<ParameterId::caloric_intake>() << ' '
<< parms.get<ParameterId::legs>() << std::endl;
return 0;
}
关于C++ 保留指向模板对象的指针集合,所有指针都派生自非模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14743239/