[英]Template specialization with variadic template for a create method
我想在一個類中創建一個靜態方法,該方法基本上只是為我創建組件,並且我想為不同的類重載此方法,但是我無法使其正常工作。 這是到目前為止我想到的最好的:
template <typename T, typename... Args>
static T* _Create(Args&&... args)
{
T* component = new T(std::forward<Args>(args)...);
return component;
}
template <typename T, typename... Args, typename std::enable_if<std::is_same<Camera, T>::value>::type* = nullptr>
static T* _Create(Args&&... args)
{
T* component = new T(std::forward<Args>(args)...);
// Do stuff with the component e.g. add it to a list
return component;
}
template <typename T, typename... Args, typename std::enable_if<std::is_base_of<CRenderer, T>::value>::type* = nullptr>
static T* _Create(Args&&... args)
{
T* component = new T(std::forward<Args>(args)...);
// Do stuff with the component e.g. add it to a list
return component;
}
但是,這當然不起作用,因為帶有“ Camera”的_Create確實與第一個和第二個函數匹配。 有人可以向正確的方向推動我嗎? 我怎樣才能做到這一點?
由於您可以訪問C ++ 17(並且不願意添加更多enable_if
),因此...
您可以使用if constexpr
所有函數合為一體!
template <typename T, typename... Args>
static T* _Create(Args&&... args)
{
T* component = new T(std::forward<Args>(args)...);
if constexpr( std::is_same<Camera, T>::value )
{
// Do stuff with the component e.g. add it to a list
}
if constexpr( std::is_base_of<CRenderer, T>::value )
{
// Do stuff with the component e.g. add it to a list
}
return component;
}
這將產生與您編寫的代碼一樣有效的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.