参见英文答案 >
Why does is_constructible claim something is constructible when it isn’t?2个
源自 this CodeReview主题:
源自 this CodeReview主题:
#include <cstddef> #include <algorithm> #include <iostream> #include <type_traits> #include <utility> template <typename T> class aggregate_wrapper : public T { private: using base = T; public: using aggregate_type = T; template <typename... Ts> aggregate_wrapper(Ts&&... xs) : base{std::forward<Ts>(xs)...} { // nop } }; struct foo_t { foo_t(int) {} }; int main() { std::cout << std::is_constructible<foo_t>::value << std::endl; std::cout << std::is_constructible<aggregate_wrapper<foo_t>>::value << std::endl; // aggregate_wrapper<foo_t> v; // won't compile }
当aggregate_wrapper< foo_t>时,std :: is_constructible< aggregate_wrapper< foo_t>> :: value怎么可能为真v;实际上没有编译?
解决方法
在C标准中,在is_constructible描述中,有一个看似无辜的引用:
Only the validity of the immediate context of the [imaginary
v
] variable initialization is considered.
然后说明它意味着什么:
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.
我的解释是,当你写:
aggregate_wrapper<foo_t> v;
您正在使用aggregate_wrapper的默认构造函数,它是存在的并且是可访问的,因此它成功,至少在直接上下文中.然后,非立即上下文包括构造函数的主体,并且失败,但这不会改变is_constructible的结果.