【发布时间】:2020-04-28 12:56:58
【问题描述】:
我决定使用以下模式自动组合各种类型的对象及其配置:
enum class Type { Car, Person };
template< Type TYPE >
struct Object;
template< Type TYPE >
struct ObjectConfig;
template<>
struct ObjectConfig< Type::Car >
{
};
// Version 1
template<>
struct Object< Type::Car >: public ObjectConfig< Type::Car > // How could I avoid this duplication???
{
};
// Version 2
template<>
struct Object< Type::Car >
{
static constexpr Type myType{ Type::Car }; // How could I avoid this duplication???
ObjectConfig< myType > m_params;
};
它旨在防错和自动,但我无法避免两次写入枚举值(这很容易出错并且根本不是自动的)。 我想写一些类似的东西(所以我想以某种方式引用专门的参数):
template< Type TYPE >
struct Object;
template<>
struct Object< Type::Car >: public ObjectConfig< TYPE >
{
};
有什么技巧可以用来实现类似的目标吗?
提前谢谢你!
请查详细代码here (code)
【问题讨论】:
-
这样的?
template <Type T=Type::Car> struct Object : public ObjectConfig< T > { }; Object<> a; -
正如我所见,您建议的代码不是模板专业化,而是具有默认值的重新定义。当然会有很多特化(汽车、人等),所以默认值是不合适的。
-
然后使用宏。