問題描述
考慮以下代碼:
#include <iostream>
#include <type_traits>
template <typename T>
struct A {
int val = 0;
template <class = typename std::enable_if<T::value>::type>
A(int n) : val(n) {};
A(...) { }
/* ... */
};
struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };
int main() {
A<YES> y(10);
A<NO> n;
std::cout << "YES: " << y.val << std::endl
<< "NO: " << n.val << std::endl;
}
我想有選擇地定義構造函數 A::A(int) 僅用于使用 enable_if 的某些類型.對于所有其他類型,默認構造函數 A::A(...) 應該是替換失敗時編譯器的默認情況.然而,這對我來說很有意義,編譯器(gcc 版本 4.9.0 20130714)仍在抱怨
I want to selectively define constructor A::A(int) only for some types using enable_if. For all other types there is default constructor A::A(...) which should be the default case for compiler when substitution fails. However this makes sense for me compiler (gcc version 4.9.0 20130714) is still complaining
sfinae.cpp:在結構 A"的實例化中:sfinae.cpp:19:11:
從這里需要 sfinae.cpp:9:5: 錯誤:
中沒有名為type"的類型'struct std::enable_if'
A(int n) : val(n) {};
sfinae.cpp: In instantiation of 'struct A': sfinae.cpp:19:11:
required from here sfinae.cpp:9:5: error: no type named 'type' in
'struct std::enable_if'
A(int n) : val(n) {};
這樣的事情對構造函數來說是可能的嗎?這是否可以與另一個構造函數(復制構造函數和移動構造函數)一起使用?
Is something like this possible for constructor? Is this possible with another constructor(s) (copy-constructor and move-constructor)?
推薦答案
With C++20
您只需將 requires
添加到模板即可實現:
With C++20
You can achieve that simply by adding requires
to the template:
template <typename U = T> requires U::value
A(int n) : val(n) { }
requires
子句獲取一個 常量表達式
,其計算結果為 true
或 false
> 因此決定是否在重載決議中考慮此方法,如果 requires 子句為真,否則忽略它.
The requires
clause gets a constant expression
that evaluates to true
or false
deciding thus whether to consider this method in the overload resolution, if the requires clause is true, or ignore it otherwise.
代碼:https://godbolt.org/z/CKTDFE
這篇關于使用 enable_if 選擇類構造函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!