我正在搜索程序中一个非常奇怪的错误的原因。我发现奇怪的是,由于某种原因,基类构造函数没有被调用。以下是复现代码:
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版本。
std::enable_if_t<false>
应该是一个硬错误,而不是替换失败。 - TartanLlamaecx
值存储到了test.test
中。这明显是一个 bug。 - 1201ProgramAlarm