TL; DR:我的問題是requires {...}可以用作constexpr bool標準的表達方式嗎?
我在標準中沒有找到任何關于它的內容,但它簡化了很多,并產生了更清晰的代碼。例如在 SFINAE 而不是enable_if, 或一些丑陋的typename = decltype(declval<>()...), 或其他東西中, 它是一個簡單的干凈的 requires-expression。
這是我的例子:
#include <type_traits>
struct foo { typedef int type; };
struct bar { ~bar() = delete; };
/**
* get_type trait, if T::type is valid, get_type<T>::type
* equal to T::type, else void
*/
// T::type is valid
template<typename T, bool = requires{typename T::type;}>
struct get_type : std::type_identity<typename T::type> {};
// T::type is invalid
template<typename T>
struct get_type<T, false> : std::type_identity<void> {};
/// Template alias, this is buggy on GCC 11.1 -> internal compiler error
template<typename T>
using get_type_t = typename get_type<T>::type;
// Tests
static_assert(std::is_same_v<get_type_t<foo>, int>);
static_assert(std::is_same_v<get_type_t<bar>, void>);
/**
* Destructible trait
*
* In libstdc -v3 this is the implementation for the testing
*
* struct __do_is_destructible_impl
* {
* template <typename _Tp, typename = decltype(declval<_Tp &>().~_Tp())>
* static true_type __test(int);
*
* template <typename>
* static false_type __test(...);
* };
*/
// This is the same:
template<typename T>
struct my_destructible_impl : std::bool_constant< requires(T t) { t.~T(); } >
{};
// Tests
static_assert(my_destructible_impl<foo>::value);
static_assert(!my_destructible_impl<bar>::value);
我發現如果我是正確的,它將評估為真或假:
將模板引數替換為模板化物體宣告中使用的 requires-expression 可能會導致在其需求中形成無效型別或運算式,或違反這些需求的語意約束。在這種情況下, requires 運算式的計算結果為 false 并且不會導致程式格式錯誤。替換和語意約束檢查按詞匯順序進行,并在遇到確定 requires 運算式結果的條件時停止。如果替換(如果有)和語意約束檢查成功,則 requires-expression 的計算結果為 true。
所以我想問一下是否requires {...}可以像我的例子一樣安全地用作constexpr bool運算式,或者不能?因為基于 cppreference.com 我不是 100% 確定,但我覺得它是,并且它使用 clang 和 GCC 編譯。但是在標準中我沒有找到任何關于它的東西(或者我可能無法正確使用 ctrl f ......)。而且我還沒有發現有人像這樣使用 requires-expression 的任何東西......
uj5u.com熱心網友回復:
requires {...}是一個要求運算式,根據expr.prim.req/p2它是一個純右值:
requires-expression 是 bool 型別的純右值,其值如下所述。出現在需求主體中的運算式是未計算的運算元。
所以是的,您可以在constexpr bool背景關系中使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467041.html
