从可变模板创建实例
Create instances from variadic templates
我试图想出一个允许通过可变模板参数创建多种类型的类,但我在编译期间得到错误:
http://ideone.com/nDWBET#include <list>
#include <memory>
struct IBaseType
{
};
class Type1 : public IBaseType
{
};
class Type2 : public IBaseType
{
};
template <typename... T>
class CreateTypes
{
public:
CreateTypes()
{
[](...){ }((m_types.push_back(std::unique_ptr<T>(new T())))...);
}
private:
std::list<std::unique_ptr<IBaseType>> m_types;
};
int main()
{
CreateTypes<Type1, Type2> createTypes;
return 0;
}
prog.cpp: In instance of ' CreateTypes::CreateTypes() [with T = {Type1, Type2}] ':
Prog.cpp:31:28: required from here
Prog.cpp:22:9:错误:无效使用void表达式
这个问题的解决方案是什么?或者我可以采取其他方法?
这里的问题是,push_back
返回void。您可以尝试使用insert
[](...) { }((m_types.insert(m_types.end(), std::unique_ptr<T>(new T())), 0)...);
从评论:push_back
= 0也可以。
[](...) { }((m_types.push_back(std::unique_ptr<T>(new T())), 0)...);
ForEveR和Xeo给了我我一直在寻找的答案,但我不得不稍微调整他们的解决方案,因为Clang不会执行空lambda的代码(我假设它被优化了,即使在调试中)。下面是我的最终解决方案(它包含了一个运行时检查,以确保总是创建正确数量的类型):
template <typename... Types>
struct VariadicTemplateCount
{
static const size_t value = sizeof...(Types);
};
// ..............
CreateTypes()
{
struct ShutTheCompiler
{
static void Up(const int[])
{
}
};
const int creation[] = {0, (m_types.push_back(std::unique_ptr<T>(new T())), 0)... };
ShutTheCompiler::Up(creation);
ASSERT(m_types.size() == VariadicTemplateCount<Types...>::value);
}
相关文章:
- 在C++中为链表类创建实例
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 如何使用Qt在D-Bus上创建/实例化配对代理
- 共创建实例消耗高 CPU
- 从与"this"相同的模板创建实例?
- 如何在不创建实例的情况下获取类的方法成员的类型?
- 创建实例化所有其他类和子系统的类的目的是什么
- 我怎么可能从尚未定义某些成员方法的类创建实例?(C++)
- godot的NetSocket如何创建实例?
- VULKAN创建实例vk_out_of_host_memory
- 如何推动在LUA脚本上使用的现有/创建/实例化类对象
- 为什么不能在不创建实例的情况下使用多态类
- 共同创建实例在 32 位上崩溃
- 创建实例时静态变量的地址
- 使用虚拟函数创建实例,为什么
- ADO 连接创建实例在 Windows Server 2003 上失败
- 使用函数中的复制构造函数创建实例的副本,该函数获取作为基对象传递的实例
- 如何从字符串中存储的类型创建实例
- ccomptr _appdomain 创建实例返回系统找不到指定的文件
- 创建实例化类数组 - 语法