假設我們有一個consteval函式或一個帶有consteval構造函式的簡單結構,它只接受一些值:
struct A
{
consteval A(int a)
{
// compile error if a < 0
if (a < 0)
throw "error";
}
};
有沒有辦法檢測這樣的建構式是否可以接受 int 的非型別模板引數?我嘗試了以下代碼但失敗了。
template <int a> concept accepted_by_A = requires() {A(a);};
int main()
{
std::cout << accepted_by_A<-1> << std::endl; // output 1 (true)
}
uj5u.com熱心網友回復:
由于對拋出的constexpr(or consteval) 函式的呼叫不是常量運算式,因此您可以檢測到:
template<int I> concept accepted_by_A=
requires() {typename std::type_identity_t<int[(A(I),1)]>;};
static_assert(accepted_by_A<1>);
static_assert(!accepted_by_A<-1>);
也可以使用 SFINAE(這將允許它constexpr在以前的語言版本中使用):
template<int,class=void> struct test : std::false_type {};
template<int I> struct test<I,decltype(void((int(*)[(A(I),1)])nullptr))> : std::true_type {};
static_assert(test<1>());
static_assert(!test<-1>());
替代專業
template<int I> struct test<I,typename voided<int[(A(I),1)]>::type> : std::true_type {};
似乎它應該作業,但沒有;在某些情況下,替換非型別模板引數很奇怪。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383314.html
上一篇:不同數量的模板變數
下一篇:為什么它在頁面頂部?
