未调用基类构造函数?

问题描述:

我正在寻找我程序中一个非常奇怪的错误的原因。我奇怪地发现,基类的构造函数不会因为某种原因而被调用。这里是重现代码:未调用基类构造函数?

struct Parent { 
    Parent() : test{9} {} 

    int test; 
}; 

template<typename T> 
struct Child : T { 
    Child() = default; 

    // Will obviously not call this one 
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr> 
    Child(Args&&... args); 
}; 

int main() { 
    Child<Parent> test; 
    std::cout << "This is a test: " << test.test << std::endl; 
} 

在我的情况下,程序只是崩溃或打印随机值。

如果我改变子类此,调用构造函数:

template<typename T> 
struct Child : T { 
    Child() = default; 
}; 

为同样的事情,构造仍称:

template<typename T> 
struct Child : T { 
    Child() {} 

    // Will obviously not call this one 
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr> 
    Child(Args&&... args); 
}; 

但与第一定义,父构造函数不被调用。 我甚至试图将父构造器标记为已删除,但它仍然编译并崩溃!

下面是与删除构造函数的代码:

struct Parent { 
    Parent() = delete; 

    int test; 
}; 

template<typename T> 
struct Child : T { 
    Child() = default; 

    // Will obviously not call this one 
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr> 
    Child(Args&&... args); 
}; 

int main() { 
    Child<Parent> test; 
    std::cout << "This is a test: " << test.test << std::endl; 
} 

我使用的Visual Studio 2015年更新在编译器3

+3

'的std :: enable_if_t '应该是一个严重的错误,而不是一个替代故障。 – TartanLlama

+0

的确你是对的。我会检查它是否仍然没有发生。 –

+0

代码不会导致未定义的行为吗?与[this]比较(http://stackoverflow.com/questions/40842044/are-checked-guard-parameter-packs-cause-of-ill-formed-programs-in-case-of-specia) –

的Bug。

如果您升级应该工作的Visual Studio 2015版本。

Microsoft's online compiler在版本19.10.24631.0(x86)似乎产生正确的输出。

GCC 6.2.0 and Clang 3.8.0 also appear to produce the correct output

+0

我使用的是2015年的最新版本...好像我必须升级到2017年...然后感谢您的帮助。 –