gpt4 book ai didi

c++ - 在成员变量中使用模板类作为模板模板参数时出错

转载 作者:搜寻专家 更新时间:2023-10-31 02:18:07 25 4
gpt4 key购买 nike

我在我的 C++ 项目中使用模板,并且在使用模板化类型作为模板模板参数时遇到问题。我认为描述它的最好方法是给出一个产生错误的例子:

template <template<class> class P, typename T>
class Foo {
P<T> baz;
};

template <class T>
class Bar {
Foo<Bar, T> memberFoo;

void makeFoo() {
Foo<Bar, T>* f = new Foo<Bar, T>();
}
};

Foo<Bar, int> globalFoo;

globalFoo 的声明不会导致错误,但是memberFoof 的声明会导致编译器错误:

error: template argument for template template parameter must be a class template or type alias template

只有在 Bar 类的声明中使用 Bar 作为模板参数时才会发生错误,但同时使用 clang 和 g++ 时也会发生。这似乎会在某处记录下来,但谷歌搜索不会产生 SO 问题或其他文档。

这种模板的使用在 C++ 中是不合法的,还是我对如何定义和使用模板有误解?如果 C++11 标准不允许这种设计架构,我可以使用什么解决方法?

最佳答案

问题是在实例化时产生了不完整的类型。 Clang 和 G++ 产生不同的错误,因为 Clang(显然)没有实现 C++11 规则,即注入(inject)的类名在用作模板模板参数时可以引用类模板本身(顺便说一句,Igor 的建议不起作用。)改变 Bar::Bar修复了这个错误,这使得 Clang 像 G++ 一样指出不完整的错误。改变 bazP<T>*允许它编译。<​​/p>

注意即使它编译,它也可能是未定义的行为。我建议重新设计您的类(class)。

关于c++ - 在成员变量中使用模板类作为模板模板参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com