std::is_constructible doesn't give the correct result [duplicate]

时光毁灭记忆、已成空白 提交于 2020-01-03 09:02:15

问题


Originated from this CodeReview topic:

#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
}

How could std::is_constructible<aggregate_wrapper<foo_t>>::value be true when aggregate_wrapper<foo_t> v; does not actually compile?


回答1:


In the C++ standard, in the is_constructible description, there is this innocent-looking quote:

Only the validity of the immediate context of the [imaginary v] variable initialization is considered.

And then a note explaining what it means:

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.

My interpretation is that when you write:

aggregate_wrapper<foo_t> v;

You are using the default constructor of aggregate_wrapper, it exists and it is accesible, so it succeeds, at least in the immediate context. Then, the non-immediate context includes the body of the constructor, and that fails, but that does not change the result of is_constructible.



来源:https://stackoverflow.com/questions/35000324/stdis-constructible-doesnt-give-the-correct-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!