如何使用C ++ 14和C ++ 1z的特性使这个可变参数模板代码更短? [英] How can I make this variadic template code shorter using features from C++14 and C++1z?
本文介绍了如何使用C ++ 14和C ++ 1z的特性使这个可变参数模板代码更短?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个代码片段,我将使用它来检查可变参数模板类型是否是唯一的:
template< typename ...>
struct is_one_of;
template< typename F>
struct is_one_of< F> {
static constexpr bool value = false;
};
template< typename F,typename S,typename ... T>
struct is_one_of< F,S,T ...> {
static constexpr bool value =
std :: is_same< F,S> :: value || is_one_of< F,T ...> :: value;
};
template< typename ...>
struct is_unique;
模板<>
struct is_unique<> {
static constexpr bool value = true;
};
template< typename F,typename ... T>
struct is_unique< F,T ...> {
static constexpr bool value =
is_unique< T ...> :: value&& !is_one_of< F,T ...> :: value;
};
int main(){
constexpr bool b = is_unique< bool,int,double> :: value;
constexpr bool c = is_unique< int,char,int> :: value;
static_assert(b == true&& c == false,!);
}
有任何方法使此代码更短和/在C ++ 14和C ++ 1z中引入?或者有更好的方法使用新的功能实现相同的效果吗?
在C ++ 1z的情况下,我的意思是: Clang和GCC版本。
解决方案
#include< type_traits&
template< typename F,typename ... Ts>
constexpr bool is_one_of =(std :: is_same< F,Ts> {} || ...);
template< typename ...>
constexpr bool is_unique = true;
template< typename F,typename ... Ts>
constexpr bool is_unique< F,Ts ...> = is_unique< Ts ...> &&& !is_one_of< F,Ts ...> ;; rel =nofollow> DEMO
This is a code snippet that I am going to use in order to check whether the variadic template types are unique:
template <typename...>
struct is_one_of;
template <typename F>
struct is_one_of<F> {
static constexpr bool value = false;
};
template <typename F, typename S, typename... T>
struct is_one_of<F, S, T...> {
static constexpr bool value =
std::is_same<F, S>::value || is_one_of<F, T...>::value;
};
template <typename...>
struct is_unique;
template <>
struct is_unique<> {
static constexpr bool value = true;
};
template <typename F, typename... T>
struct is_unique<F, T...> {
static constexpr bool value =
is_unique<T...>::value && !is_one_of<F, T...>::value;
};
int main() {
constexpr bool b = is_unique<bool, int, double>::value;
constexpr bool c = is_unique<int, char, int>::value;
static_assert(b == true && c == false, "!");
}
Is there any way to make this code shorter and/or more concise using features introduced in C++14 and C++1z? Or is there a better way to achieve the same effect using the new features?
In the case of C++1z I mean: features that are already available in the newest versions of Clang and GCC.
解决方案 #include <type_traits>
template <typename F, typename... Ts>
constexpr bool is_one_of = (std::is_same<F, Ts>{} || ...);
template <typename...>
constexpr bool is_unique = true;
template <typename F, typename... Ts>
constexpr bool is_unique<F, Ts...> = is_unique<Ts...> && !is_one_of<F, Ts...>;
这篇关于如何使用C ++ 14和C ++ 1z的特性使这个可变参数模板代码更短?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文