error: aggregate ‘food_type a’ has incomplete type and cannot be defined

error: aggregate ‘food_type a’ has incomplete type and cannot be defined

编译器不允许我运行这段代码:

error: aggregate ‘food_type a’ has incomplete type and cannot be defined

除非我在实例化 af1f2f3 后添加括号 (),这会阻止 cout 函数显示任何内容.为什么会这样?

#include <iostream>

enum class Animal { Cat, Dog, Duck};

class Food
{
public:
    Food()
    {
        std::cout<<"Food called"<<std::endl;
    }
};

template <enum Animal,class food_type>
class Ecosystem;

template<>
class Ecosystem<Animal::Cat,class food_type>
{
public:
    Ecosystem()
    {
        std::cout<<"Cat constructor called"<<std::endl;
        food_type a;
    }
};

template <>
class Ecosystem<Animal::Dog,class food_type>
{
public:
    Ecosystem()
    {
        std::cout<<"Dog constructor called"<<std::endl;
        food_type a;
    }
};


template <>
class Ecosystem<Animal::Duck,class food_type>
{
public:
    Ecosystem()
    {
        std::cout<<"Duck constructor called"<<std::endl;
        food_type a;
    }
};

int main()
{
    Ecosystem<Animal::Cat,Food> f1;
    Ecosystem<Animal::Dog,Food> f2;
    Ecosystem<Animal::Duck,Food> f3;
    return 0;
}

如果您尝试部分专门化模板,应该这样做:

template<class food_type>
class Ecosystem<Animal::Cat,food_type>

而不是:

template<>
class Ecosystem<Animal::Cat,class food_type>

在第二种情况下,您实际上正在做的是基于不完整类型 class food_type 的完全专业化,这就是导致错误的原因。