std::is_constructible, std::is_trivially_constructible, std::is_nothrow_constructible
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class T, class... Args > struct is_constructible; |
(1) | (C++11 起) |
template< class T, class... Args > struct is_trivially_constructible; |
(2) | (C++11 起) |
template< class T, class... Args > struct is_nothrow_constructible; |
(3) | (C++11 起) |
1) 如果
為此檢查的目的,變數定義從不解釋為函式宣告,且 std::declval 的使用不被認為是 odr-use。訪問檢查 的執行就像從與
T
是物件或引用型別,且變數定義 T obj(std::declval<Args>()...); 是良構的,則提供成員常量 value
等於 true。在所有其他情況下,value
為 false。為此檢查的目的,變數定義從不解釋為函式宣告,且 std::declval 的使用不被認為是 odr-use。訪問檢查 的執行就像從與
T
和 Args
中的任何型別都無關的上下文一樣。只考慮變數定義的即時上下文的有效性。3) 同 (1),但變數定義是
noexcept
的。如果 T
或引數包 Args
中的任何型別不是完整型別、(可能經 cv 限定的)void,或未知邊界陣列,則行為未定義。
如果上述模板的例項化直接或間接依賴於不完整型別,並且該例項化在該型別假設完成時可能產生不同的結果,則行為未定義。
如果程式為此頁上描述的任何模板新增特化,則行為未定義。
目錄 |
[編輯] 輔助變數模板
template< class T, class... Args > inline constexpr bool is_constructible_v = |
(C++17 起) | |
template< class T, class... Args > inline constexpr bool is_trivially_constructible_v = |
(C++17 起) | |
template< class T, class... Args > inline constexpr bool is_nothrow_constructible_v = |
(C++17 起) | |
繼承自 std::integral_constant
成員常量
value [靜態] |
true 如果 T 可從 Args... 構造,否則為 false(public static 成員常量) |
成員函式
operator bool |
將物件轉換為 bool,返回 value (公開成員函式) |
operator() (C++14) |
返回 value (公開成員函式) |
成員型別
型別 | 定義 |
value_type
|
bool |
型別
|
std::integral_constant<bool, value> |
[編輯] 注意
在許多實現中,is_nothrow_constructible
也檢查解構函式是否丟擲,因為它實際上是 noexcept(T(arg))。is_trivially_constructible
也適用相同的情況,在這些實現中,它也要求解構函式是平凡的:GCC bug 51452 LWG issue 2116。
[編輯] 示例
執行此程式碼
#include <iostream> #include <type_traits> class Foo { int v1; double v2; public: Foo(int n) : v1(n), v2() {} Foo(int n, double f) noexcept : v1(n), v2(f) {} }; int main() { auto is = [](bool o) { return (o ? "\t" "is " : "\t" "isn't "); }; std::cout << "Foo ...\n" << is(std::is_trivially_constructible_v<Foo, const Foo&>) << "Trivially-constructible from const Foo&\n" << is(std::is_trivially_constructible_v<Foo, int>) << "Trivially-constructible from int\n" << is(std::is_constructible_v<Foo, int>) << "Constructible from int\n" << is(std::is_nothrow_constructible_v<Foo, int>) << "Nothrow-constructible from int\n" << is(std::is_nothrow_constructible_v<Foo, int, double>) << "Nothrow-constructible from int and double\n"; }
輸出
Foo ... is Trivially-constructible from const Foo& isn't Trivially-constructible from int is Constructible from int isn't Nothrow-constructible from int is Nothrow-constructible from int and double
[編輯] 參閱
檢查型別是否具有預設建構函式 (類模板) | |
(C++11)(C++11)(C++11) |
檢查型別是否具有複製建構函式 (類模板) |
(C++11)(C++11)(C++11) |
檢查型別是否可以從右值引用構造 (類模板) |
(C++20) |
指定該型別的變數可以從一組引數型別構造或繫結 (概念) |