我正在尝试使用返回类型不断变化的模板化可变参数。如果参数个数为1,则应返回指向唯一参数的指针,否则应返回该参数的指针元组:
int var = 0;
A *ptr_A = foo<A>(var);
auto *[ptr_A, ptr_B] = foo<A, B>(var);
这是我到目前为止的代码
template<typename T>
T* AddComp(EntityId entityID)
{
componentPool<T>* pool = GetOrCreatePool<T>();
return pool->Create(entityID);
}
template <typename... Args>
decltype(auto) AddComponent(EntityId entityID)
{
if constexpr (sizeof...(Args) == 1)
{
return AddComp <Args>(entityID);
}
else
{
return std::tuple<decltype(AddComponent<Args>({}))... > {AddComponent<Args>(entityID)...};
}
}
但是我遇到了几个错误:
如果A *ptr_A = foo<A>(var);
VS表示他不能从void转换为A *,则表示decltype(auto)正在以某种方式变为void
并在return AddComp <Args>(entityID);
VS中表示必须扩展Args参数包。即使它是单个参数,我是否仍需要以某种方式扩展Args?
谢谢!
编辑:
根据要求,我提供了一个最小的例子
using EntityId = size_t;
class A
{
public:
int a;
};
class B
{
public:
int b;
};
class componentsManager
{
public:
template<typename T>
T* AddComp(EntityId entityID)
{
return new T();
}
template <typename... Args>
decltype(auto) AddComponent(EntityId entityID)
{
if constexpr (sizeof...(Args) == 1)
{
return AddComp <Args>(entityID);
}
else
{
return std::tuple<decltype(AddComponent<Args>({}))... > {AddComponent<Args>(entityID)...};
}
}
};
componentsManager m_manager;
EntityId id;
A *ptr_A1 = m_manager.AddComponent <A>(id);
auto *[ptr_A2, ptr_B] = m_manager.AddComponent<A, B>(id);// This will only compile in c++17 i believe, i am using c++14
编辑2:
简单明了
if constexpr (sizeof...(Args) == 1)
{
return AddComp<Args...>(entityID);
}
这是与C ++ 14一起使用的解决方案:
template <typename T>
decltype(auto) AddComponent(EntityId entityID)
{
return AddComp<T>(entityID);
}
template <typename... Args>
decltype(auto) AddComponent(
std::enable_if_t<(sizeof...(Args) > 1), EntityId> entityID)
{
return std::tuple<decltype(AddComponent<Args>({}))...>{
AddComponent<Args>(entityID)...};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句