[英]Construct an 'is_template_instantiable' type trait in C++
是否可以在C ++中構造一個類型特征,用於檢查給定模板類型是否可以使用給定類型作為模板參數進行實例化? 如果有可能,怎么辦呢?
例如:
static_assert(is_template_instantiable_v<std::optional, int, int>);
static_assert(is_template_instantiable_v<std::vector, double>);
第一個斷言將失敗,因為std::optional
只需要一個模板參數。 第二個斷言不會失敗, std::vector
可能只用一個模板參數進行實例化,因為它的第二個模板參數有一個默認值。
如果可能的話,在下列情況下是否可以讓類型特征為假(並且不會觸發編譯錯誤):
static_assert(is_template_instantiable_v<std::vector, int &>);
因為std::vector
可能無法使用引用作為其值類型進行實例化。
我的猜測是第一個例子可能是可行的復制,而第二個例子不能僅使用標准C ++代碼完成。
我假設第一個要求是基於檢測習語的方法是可行的:
namespace detail
{
template<template<typename...> typename T, typename AlwaysVoid, typename... Ts>
struct is_template_instantiable :
std::false_type {};
template<template<typename...> typename T, typename... Ts>
struct is_template_instantiable<T, std::void_t<T<Ts...>>, Ts...> :
std::true_type {};
template<template<typename...> typename T, typename... Ts>
inline constexpr auto is_template_instantiable_v =
is_template_instantiable<T, void, Ts...>::value;
}
然后,用:
template<typename T = void>
struct X{};
它產生:
static_assert(detail::is_template_instantiable_v<X>);
static_assert(detail::is_template_instantiable_v<X, void>);
static_assert(!detail::is_template_instantiable_v<X, void, int>);
然而,有了這種特質,我無法解決第二個挑戰......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.