测试 std::common_type 是否存在
Test if std::common_type exists
我想编写一个辅助模板来检查模板参数包是否具有通用类型,即,如果将 std::common_type
应用于包是否定义了一个类型。
在 SFINAE 中使用 std::void_t 我得出了以下定义:
template<typename... Types, typename Enable = void>
struct has_common_type : std::false_type
{ };
template<typename... Types>
struct has_common_type<Types..., std::void_t<std::common_type<Types...>::type>> : std::true_type
{ };
然而这不起作用,因为模板参数包必须是最后一个参数。编译器引发以下错误:
error: template parameter pack must be the last template parameter
template<typename... Types, typename Enable = void>
如何定义这样一个模板?
选项#1
template <typename... Ts>
using has_common_type = std::experimental::is_detected<std::common_type_t, Ts...>;
选项#2
template <typename AlwaysVoid, typename... Ts>
struct has_common_type_impl : std::false_type {};
template <typename... Ts>
struct has_common_type_impl<std::void_t<std::common_type_t<Ts...>>, Ts...> : std::true_type {};
template <typename... Ts>
using has_common_type = typename has_common_type_impl<void, Ts...>::type;
我想编写一个辅助模板来检查模板参数包是否具有通用类型,即,如果将 std::common_type
应用于包是否定义了一个类型。
在 SFINAE 中使用 std::void_t 我得出了以下定义:
template<typename... Types, typename Enable = void>
struct has_common_type : std::false_type
{ };
template<typename... Types>
struct has_common_type<Types..., std::void_t<std::common_type<Types...>::type>> : std::true_type
{ };
然而这不起作用,因为模板参数包必须是最后一个参数。编译器引发以下错误:
error: template parameter pack must be the last template parameter
template<typename... Types, typename Enable = void>
如何定义这样一个模板?
选项#1
template <typename... Ts>
using has_common_type = std::experimental::is_detected<std::common_type_t, Ts...>;
选项#2
template <typename AlwaysVoid, typename... Ts>
struct has_common_type_impl : std::false_type {};
template <typename... Ts>
struct has_common_type_impl<std::void_t<std::common_type_t<Ts...>>, Ts...> : std::true_type {};
template <typename... Ts>
using has_common_type = typename has_common_type_impl<void, Ts...>::type;