gpt4 book ai didi

c++ - 为什么 is_constructible 声称某些东西不是可构造的?

转载 作者:IT老高 更新时间:2023-10-28 22:34:35 25 4
gpt4 key购买 nike

以下程序在使用 GCC 4.7 和 clang 3.2 编译时,会产生“1”作为输出。

#include <type_traits>

struct foo {
template<typename T>
foo(T) {
static_assert(not std::is_same<int, T>(), "no ints please");
}
};

#include <iostream>
int main() {
std::cout << std::is_constructible<foo, int>();
}

这令人困惑。 foo 显然不能从 int 构造!如果我将 main 更改为以下内容,两个编译器都会因为静态断言失败而拒绝它:

int main() {
foo(0);
}

为什么两个编译器都说它是可构造的?

最佳答案

这是标准必须说的(§20.9.5/6),我强调:

Given the following function prototype:

template <class T>
typename add_rvalue_reference<T>::type create();

the predicate condition for a template specialization is_constructible<T, Args...> shall be satisfied if and only if the following variable definition would be well-formed for some invented variable t:

T t(create<Args>()...);

[ Note: These tokens are never interpreted as a function declaration. —end note ]

Access checking is performed as if in a context unrelated to T and any of the Args. Only the validity of the immediate context of the variable initialization is considered. [ Note: The evaluation of the initialization can result in side effects such as the instantiation of class template specializations and function template specializations, the generation of implicitly-defined functions, and so on. Such side effects are not in the “immediate context” and can result in the program being ill-formed. —end note ]

只有在模板构造函数被实例化时,断言才会失败。但是,正如注释中所澄清的那样,该断言不在所考虑的变量定义的直接上下文中,因此不会影响其“有效性”。因此编译器可以将该定义视为有效,从而声称 foo确实可以从 int 构造,即使实际上试图构造一个 foo来自 int导致程序格式错误。

请注意,编译器也可以,而不是 is_constructible yield false,只是根据断言拒绝原始程序,即使两者都没有。

关于c++ - 为什么 is_constructible 声称某些东西不是可构造的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14815998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com