Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从可变模板创建实例_C++_Templates_C++11_Variadic Templates - Fatal编程技术网

C++ 从可变模板创建实例

C++ 从可变模板创建实例,c++,templates,c++11,variadic-templates,C++,Templates,C++11,Variadic Templates,我正在尝试创建一个类,该类允许通过可变模板参数创建多个类型,但在编译过程中出现错误: #包括 #包括 结构IBaseType { }; 类类型1:公共IBaseType { }; 类别类型2:公共IBaseType { }; 模板 类CreateTypes { 公众: CreateTypes() { [](…){}((m_-types.push_-back(std::unique_-ptr(new T()))))); } 私人: std::列出m_类型; }; int main() { Cre

我正在尝试创建一个类,该类允许通过可变模板参数创建多个类型,但在编译过程中出现错误:

#包括
#包括
结构IBaseType
{
};
类类型1:公共IBaseType
{
};
类别类型2:公共IBaseType
{
};
模板
类CreateTypes
{
公众:
CreateTypes()
{
[](…){}((m_-types.push_-back(std::unique_-ptr(new T())))));
}
私人:
std::列出m_类型;
};
int main()
{
CreateTypes CreateTypes;
返回0;
}
prog.cpp:在“CreateTypes::CreateTypes()[with T={Type1,Type2}]”的实例化中:
进度cpp:31:28:从这里开始需要
程序cpp:22:9:错误:无效表达式的使用无效


解决这个问题的办法是什么?或者我可以采取另一种方法吗?

这里的问题是,
push\u back
返回void。您可以尝试使用
insert

[](...) { }((m_types.insert(m_types.end(), std::unique_ptr<T>(new T())), 0)...);

ForEveR和Xeo给了我我一直在寻找的答案,但我不得不稍微调整他们的解决方案,因为Clang不会执行空lambda的代码(我假设它被优化了,即使是在调试中)。下面是我的最终解决方案(它包含运行时检查,以确保始终创建正确数量的类型):

模板
结构变量模板计数
{
静态常量大小\u t值=sizeof…(类型);
};
// ..............
CreateTypes()
{
结构关闭编译器
{
静态无效(常量int[])
{
}
};
const int creation[]={0,(m_types.push_back(std::unique_ptr(new T())),0);
关闭compiler::Up(创建);
断言(m_types.size()==VariableTemplateCount::value);
}

想知道。。。Clang无法使用segfault编译它。我在Xcode中使用Clang,它无法使用
std::unique_ptr
进行编译,但可以使用原始指针进行编译。“但是,如果我将列表更改为
std::list
,lambda更改为
m类型。推回(new T())
它工作正常。”=>?我仍然得到这个代码的错误:(我错过了什么吗?)奇怪的是,我现在也得到了错误。我将收回关于原始指针工作的说法。了不起的在ideone中有效,但在Clang(Xcode)中无效。为什么push_back适用于原始指针,而不是智能指针?@MarkIngram适用于Ubuntu上的Clang3.2。您使用change unique_ptr编写代码,将其更改为T*使gcc中有关void类型的clang和编译错误崩溃。省略号(C-style varargs)需要普通类型,并且从
insert
返回的迭代器很可能不是普通类型。用<代码>(插入式ExPR,0)< /代码>。好,C++看起来越来越神秘;我想提到的是,如果列表中元素的顺序很重要,您必须在这里使用递归解决方案。@catscradle:或使用列表初始化(例如
int tmp[]={0,(expr,0)…}
-如果变量包为空,则额外的
0
)。
[](...) { }((m_types.insert(m_types.end(), std::unique_ptr<T>(new T())), 0)...);
[](...) { }((m_types.push_back(std::unique_ptr<T>(new T())), 0)...);
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);
}