成对布尔和C ++模板中 [英] Pairwise bool and in c++ template

查看:47
本文介绍了成对布尔和C ++模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个模板,该模板接受任意数量的参数,并在这些值上找到布尔AND.

 模板< bool ... Vs>struct meta_bool_and;模板< bool V>struct meta_bool_and:std :: integral_constant< bool,V>{};模板< bool V,bool ... Vs>struct meta_bool_and:std :: integral_constant< bool,V&&meta_bool_and< Vs ...> :: value>{}; 

但是,我无法通过以下消息进行编译

 错误:使用2个模板参数重新声明struct meta_bool_and:std :: integral_constant< bool,V&&meta_bool_and< Vs ...> :: value>{}; 

如何解决此问题?

解决方案

您已经编写了重新定义而不是部分专业化.为了提供专门化,您必须指定要专门研究的属性.

这将起作用:

  #include< type_traits>模板< bool ... Vs>struct meta_bool_and;模板< bool V>结构meta_bool_and< V>:std :: integral_constant< bool,V>{};//^^^模板< bool V,bool ... Vs>结构meta_bool_and< V,Vs ...>:std :: integral_constant< bool,V&&meta_bool_and< Vs ...> :: value>{};//^^^^^^^^^^^ 

作为改进,请考虑是否要支持空连接(通常定义为true).如果是这样,请不要专注于 meta_bool_and< bool> ,而要专注于 meta_bool_and<> (源自 std :: true_type ).

I am writing a template that takes a arbitrary number of arguments and find the Boolean AND on these value.

template <bool... Vs> struct meta_bool_and;

template <bool V> struct meta_bool_and : std::integral_constant<bool, V> {}; 

template <bool V, bool... Vs> 
struct meta_bool_and : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 

However, I failed to compile by the following message

 error: redeclared with 2 template parameters
 struct meta_bool_and : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 

How can I fix this problem?

解决方案

You have written a re-definition instead of a partial specialization. In order to provide a specialization, you must specify what properties you specialize on.

This will work:

#include <type_traits>

template <bool... Vs> struct meta_bool_and;

template <bool V> struct meta_bool_and<V> : std::integral_constant<bool, V> {};
//                                    ^^^

template <bool V, bool... Vs> 
struct meta_bool_and<V, Vs...> : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 
//                  ^^^^^^^^^^

As an improvement, think whether you want to support the empty conjunction (typically defined as true). If so, don't specialize on meta_bool_and<bool> but on meta_bool_and<> (derived from std::true_type).

这篇关于成对布尔和C ++模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆