gpt4 book ai didi

c++ - 创建显式专用模板类对象会产生 "object has initializer but incomplete type"错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:02:59 25 4
gpt4 key购买 nike

简单的案例。我不太明白为什么括号对于调用显式实例化模板的默认构造函数是必需的。而且,为什么调用显式实例化模板的非默认 ctor 会给我“不完整类型”错误?

非常感谢!

// X.h
template <const int MODE>
class X{
public:
X() = default;
X(int& a) {++a;}
// define X here
};
// declare the explicit specialization
template <> class X<1>;
// Then define the default behaviors of X.


// X.cpp
#include "X.h"
template <>
class X<1>{
public:
X() = default;
X(int& a) {--a;}
// define X<1>
};
// Then specialize behavior.


// main.cpp
#include "X.h"

int main(){
X<2> x_2; // fine, instantiates the default version
X<1> x_1(); // Edit: A function declaration, as pointed out in the comment.
X<1> x_1_1; // error: aggregate ‘X<1> x_1_1’ has incomplete type and cannot be defined
int a = 0;
X<1> x_1_2(a); // error: variable ‘X<1> x_1_2’ has initializer but incomplete type
}

最佳答案

正如其他人指出的那样X<1> x_1();只是一个函数声明,所以它实际上并没有实例化 X<1> 类型的对象.对于 incomplete type错误:您必须将 X<1> 的整个声明进入头文件(不仅仅是前向声明,就像你现在所做的那样)。您可以将实现 放在cpp 文件中,但是任何使用类型为X<1> 的对象(不仅是指向对象的指针)的人都可以。 (在这种情况下:main)必须知道它有多大以及它提供什么方法​​。

您的困惑可能部分源于您在示例中使用特化的方式:在您的特化中,与通用模板唯一不同的是其中一个构造函数的定义(所有签名保持不变)。所以你可能认为编译器可以自己解决这个问题。事实上,它不可能这样做,因为您的专用类可能看起来与非专用模板完全不同(具有不同的构造函数、不同的成员/成员函数)。像这样:

template <int I>
struct X {
bool hello(int x, int y);
};

template<>
struct X<1> {
int goodbye(std::string x);
};

如果编译器只看到template<> struct X<1>;相反,它应该如何找出这个类的接口(interface)?

关于c++ - 创建显式专用模板类对象会产生 "object has initializer but incomplete type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26343111/

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