2016-11-29 137 views
3

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

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) –

回答