![](/img/trans.png)
[英]Can we assume std::is_default_constructible<T> and std::is_constructible<T> to be equal?
[英]std::is_default_constructible<T> error, if constructor is private
我有以下片段
#include <type_traits>
#include <boost/type_traits.hpp>
class C { C() { } };
int main()
{
static_assert(!boost::has_trivial_default_constructor<C>::value, "Constructible");
static_assert(!std::is_default_constructible<C>::value, "Constructible");
}
條件不相等,但第一個條件可以正常工作,第二個構造給出錯誤,該構造函數是私有的。 編譯器gcc 4.7 ...那么,這是gcc錯誤,還是由標准定義的?
http://liveworkspace.org/code/NDQyMD $ 5
好。 由於這種情況確實不平等-我們可以使用類似這樣的方法
#include <type_traits>
#include <boost/type_traits.hpp>
class C { private: C() noexcept(false) { } };
int main()
{
static_assert(!boost::has_nothrow_constructor<C>::value, "Constructible");
static_assert(!std::is_nothrow_constructible<C>::value, "Constructible");
}
http://liveworkspace.org/code/NDQyMD $ 24
無論如何,我知道,static_assert不應失敗,因為類型實際上不是默認可構造的/不可構造的。 問題是:為什么會有編譯錯誤,不是由我的靜態斷言引起的?
看起來像一個編譯器錯誤。 讓我們看一下SFINAE的以下示例(在g++
的type_traits
標頭中使用了類似的實現)
#include <type_traits>
class Private
{
Private()
{
}
};
class Delete
{
Delete() = delete;
};
struct is_default_constructible_impl
{
template<typename T, typename = decltype(T())>
static std::true_type test(int);
template<typename>
static std::false_type test(...);
};
template <class T>
struct is_default_constructible: decltype(is_default_constructible_impl::test<T>(0))
{
};
int main()
{
static_assert(is_default_constructible<Private>::value, "Private is not constructible");
static_assert(is_default_constructible<Delete>::value, "Delete is not constructible");
}
第二個assert可以按預期工作,我們不能推斷Delete
類型,因為該類只有一個已刪除的構造函數。 但是,當編譯器嘗試推斷Private()
類型時,會出現錯誤: Private::Private() is private
。 因此,我們有兩個帶有私有構造函數的類,但是其中一個給出了錯誤,第二個給出了錯誤。 我認為這種行為是錯誤的,但是我在標准中找不到確認。
PS全部提供的代碼均由clang編譯,沒有任何錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.