C++ 模板和别名
C++ templates and alias
这将在库中使用,与示例不同,下面的示例只是为了解释问题。
我有一个模板 class BaseType
具有模板专业化。
template<class...>
class BaseType; //Forward declare
template<typename T>
BaseType<T> { /* ...implementation 1... */ };
template<typename T, typename R>
BaseType<T,R> { /* ...implementation 2... */ };
我现在要为 shared_ptr<BaseType>
模板创建一个别名。
为其中一个模板版本执行此操作效果很好。
template<typename T>
using SlotType = std::shared_ptr<BaseType<T> >;
using EventArgSlot = SlotType<EventArgs>;
EventArgSlot slot1;
但是我应该如何定义别名使其也支持这个:
using MessageIntegerSlot = SlotType<MessageArgs, int>;
MessageIntegerSlot slot2;
仅添加一个具有相同模板参数的别名是行不通的:
template<typename T, typename R>
using SlotType = std::shared_ptr<BaseType<T,R> >;
这可以在 C++11/14 中解决吗?
您可以利用 parameter pack 并将 SlotType
的定义更改为
template<typename... T>
using SlotType = std::shared_ptr<BaseType<T...> >;
然后
using EventArgSlot = SlotType<EventArgs>; // use the 1st specialization of BaseType
using MessageIntegerSlot = SlotType<MessageArgs, int>; // use the 2nd specialization of BaseType
这将在库中使用,与示例不同,下面的示例只是为了解释问题。
我有一个模板 class BaseType
具有模板专业化。
template<class...>
class BaseType; //Forward declare
template<typename T>
BaseType<T> { /* ...implementation 1... */ };
template<typename T, typename R>
BaseType<T,R> { /* ...implementation 2... */ };
我现在要为 shared_ptr<BaseType>
模板创建一个别名。
为其中一个模板版本执行此操作效果很好。
template<typename T>
using SlotType = std::shared_ptr<BaseType<T> >;
using EventArgSlot = SlotType<EventArgs>;
EventArgSlot slot1;
但是我应该如何定义别名使其也支持这个:
using MessageIntegerSlot = SlotType<MessageArgs, int>;
MessageIntegerSlot slot2;
仅添加一个具有相同模板参数的别名是行不通的:
template<typename T, typename R>
using SlotType = std::shared_ptr<BaseType<T,R> >;
这可以在 C++11/14 中解决吗?
您可以利用 parameter pack 并将 SlotType
的定义更改为
template<typename... T>
using SlotType = std::shared_ptr<BaseType<T...> >;
然后
using EventArgSlot = SlotType<EventArgs>; // use the 1st specialization of BaseType
using MessageIntegerSlot = SlotType<MessageArgs, int>; // use the 2nd specialization of BaseType