C++ 我可以使用traits指定变体的类型列表吗?
我正在试验一些静态多态技术和c++17模板。我已经设法使用CRTP实现了多态性,然后使用一个变体容器来存储我的类型,这样它们就不需要公共基类(这将使我回到运行时多态性)C++ 我可以使用traits指定变体的类型列表吗?,c++,templates,c++17,variant,crtp,C++,Templates,C++17,Variant,Crtp,我正在试验一些静态多态技术和c++17模板。我已经设法使用CRTP实现了多态性,然后使用一个变体容器来存储我的类型,这样它们就不需要公共基类(这将使我回到运行时多态性) #包括 #包括 #包括 #包括 模板 类动物 { 公众: virtual~Animal()=默认值; 空隙噪声() { 派生()->noiseImpl(); } 私人: void noiseImpl() { std::cout我认为不可能自动确定从基类继承的所有类。一般来说,这是不可能的,因为不同的继承类可以在不同的编译单元中定
#包括
#包括
#包括
#包括
模板
类动物
{
公众:
virtual~Animal()=默认值;
空隙噪声()
{
派生()->noiseImpl();
}
私人:
void noiseImpl()
{
std::cout我认为不可能自动确定从基类继承的所有类。一般来说,这是不可能的,因为不同的继承类可以在不同的编译单元中定义
您可以做的是在某个MPL类型序列中“注册”这些继承的类,然后使用它定义您的变体
类型。例如,使用boost::hana
:
constexpr auto types = boost::hana::tuple_t<char, short, int, long>;
using variant = decltype(boost::hana::unpack(
types, boost::hana::template_<std::variant>))::type;
static_assert(std::is_same_v<variant, std::variant<char, short, int, long>>);
constexpr auto-types=boost::hana::tuple\t;
使用variant=decltype(boost::hana::unpack(
类型,boost::hana::template):::类型;
静态断言(std::is_same_v);
在你的情况下,这将是:
constexpr auto types = boost::hana::tuple_t<Dog, Cat>;
constexpr auto-types=boost::hana::tuple\t;
啊,这看起来很方便,但我想考虑的是,从Animal派生的用户定义类型可以存储在容器中,而不必预先指定所有这些类型。类似于使用Animal*
存储它们,但我想看看是否可以避免使用运行时多态性。@nitronoid您可以使用类型er来实现这一点有关技术,请参阅,例如,运行时多态性是无法避免的,但它隐藏在用户的内部。请查找std::vector backpack;
,在您的案例中,它将是动物的载体。
constexpr auto types = boost::hana::tuple_t<Dog, Cat>;