我已經找了很長時間了,我可能只是不知道該用什么詞來找到它。
我有一個接受型別的模板類,并且希望建構式根據該型別是否為指標而有所不同。這是一些代碼來解釋我的意思。
template <class T> class Example
{
bool choice;
public:
//Only if T is not a pointer type
Example() : choice{false}
{}
//Only if T is a pointer type
Example(bool choice) : choice{choice}
{}
}
我已經嘗試過std::enable_if,std::is_pointer<T>但沒有運氣。
uj5u.com熱心網友回復:
您可以專攻整個班級:
template <class T> struct Example {
bool choice;
Example() : choice{false} {}
};
template <class T> struct Example<T*> {
bool choice;
Example(bool choice) : choice{choice} {}
};
int main() {
Example<int> e;
Example<int*> f(false);
}
或通過std::enable_if:
#include <type_traits>
template <class T> struct Example {
bool choice;
template <typename U = T, std::enable_if_t<!std::is_pointer_v<U>,bool> = true>
Example() : choice{false} {}
template <typename U = T, std::enable_if_t<std::is_pointer_v<U>,bool> = true>
Example(bool choice) : choice{choice} {}
};
int main() {
Example<int> e;
Example<int*> f(false);
}
的條件之一std::enable_if是true。要么std::is_pointer_v<T>是true第一個建構式是替換失敗,要么是false第二個被丟棄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445342.html
標籤:C
上一篇:使用CRTP類呼叫std::make_pair中的奇怪行為
下一篇:如何在Qt中使用子專案?
