gpt4 book ai didi

c++ - g++ 编译器无法编译完全定义的类型

转载 作者:太空狗 更新时间:2023-10-29 21:13:11 27 4
gpt4 key购买 nike

我试图在同一结构中使用该结构的静态实例,但 g++ 编译器告诉我:

C:\Temp\cs2cpp_tries\test\test.cpp: In instantiation of 'struct Static<Test<int> >':
C:\Temp\cs2cpp_tries\test\test.cpp:16:19: required from 'struct Test<int>'
C:\Temp\cs2cpp_tries\test\test.cpp:20:12: required from here
C:\Temp\cs2cpp_tries\test\test.cpp:6:4: error: 'Static<T>::t' has incomplete type
T t;
^
C:\Temp\cs2cpp_tries\test\test.cpp:10:8: note: declaration of 'struct Test<int>'
struct Test
^~~~

这是代码示例。您可以看到类型已定义,但 g++ 仍然不喜欢它。

#include <iostream>

template < typename T >
struct Static
{
T t;
};

template < typename T >
struct Test
{
static Static<Test<T>> t;
};

template < typename T >
Static< Test<T> > Test<T>::t;

int main (int argc, char **argv)
{
Test<int> t;
return 0;
}

但是如果你删除 template < typename T >从测试类和代码变得完全可编译

#include <iostream>

template < typename T >
struct Static
{
T t;
};

struct Test
{
static Static<Test> t;
};

Static< Test > Test::t;

int main (int argc, char **argv)
{
Test t;
return 0;
}

最佳答案

似乎是 gcc 错误,来自 [class.static]

The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void.

所以不管Test<T>Static<Test<T>>具有完整的类型,应该允许声明。

来自 [temp.inst]

the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type


The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, [...] static data members [...]

表示我们第一次使用 Test<int>声明一个变量,Test<int>必须是完全定义的类型,所以 Test<int>被隐式实例化,但是 Static<Test<int>>不需要是完全定义的对象类型,因为它仍然只是声明的。

有趣的是,gcc 编译得很好

template<typename>
struct Static;

template<typename T>
struct Test
{
static Static<Test<T>> t;
};

template<typename T>
Static<Test<T>> Test<T>::t;

Test<int> t;
//auto u = t.t; // error, now requires a completely-defined type

Live

尽管Static甚至没有定义,Test::t永远不需要是完全定义的类型。

关于c++ - g++ 编译器无法编译完全定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45081096/

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