简体   繁体   English

删除的构造函数和模板

[英]Deleted constructor and template

Consider the following:考虑以下:

template<typename T>
class A
{
public:
    A(int a)
    {}

    A() = delete;
};

class B
{
public:
    B()
    {
        A<int> a;
    }
};

Of course this code does not compile because class B's constructor is attempting to default-construct a class A object and I've explicitly deleted that constructor.当然,这段代码无法编译,因为 B 类的构造函数试图默认构造一个 A 类对象,而我已经明确删除了该构造函数。 All well and good.一切都很好。

However, if I make B a class template但是,如果我将 B 设为类模板

template<typename T>
class A
{
public:
    A(int a)
    {}

    A() = delete;
};

template<typename T>
class B
{
public:
    B()
    {
        A<int> a;
    }
};

then the code does compile and it seems I can now default-construct an instance of class A.然后代码确实编译了,看来我现在可以默认构造 A 类的实例。

Why is this?为什么是这样? What am I missing?我错过了什么?

Thanks.谢谢。

D'oh!哦! It appears that the compiler doesn't see the error until it attempts to instantiate a class from the template.似乎编译器在尝试从模板实例化一个类之前不会看到错误。

Actually trying to create an object of type B<> generates the expected error.实际上尝试创建 B<> 类型的对象会产生预期的错误。

Sorry if I wasted your time.对不起,如果我浪费了你的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM