为什么模板类有未使用的类型?

时间:2015-02-26 20:17:29

标签: c++ templates generic-programming template-classes boost-units

我正在审查boost单元库,我很困惑为什么boost :: units :: unit类有一个额外的模板参数。这是一个例子:

http://www.boost.org/doc/libs/1_57_0/boost/units/unit.hpp

template<class Dim,class System, class Enable>
class unit
{
    public:
        typedef unit<Dim, System>   unit_type;
        typedef unit<Dim,System>    this_type;
        typedef Dim                 dimension_type; 
        typedef System              system_type;

        unit() { }
        unit(const this_type&) { }
        //~unit() { }  

        this_type& operator=(const this_type&) { return *this; }

        // sun will ignore errors resulting from templates
        // instantiated in the return type of a function.
        // Make sure that we get an error anyway by putting.
        // the check in the destructor.
        #ifdef __SUNPRO_CC
        ~unit() {
            BOOST_MPL_ASSERT((detail::check_system<System, Dim>));
            BOOST_MPL_ASSERT((is_dimension_list<Dim>));
        }
        #else
    private:
        BOOST_MPL_ASSERT((detail::check_system<System, Dim>));
        BOOST_MPL_ASSERT((is_dimension_list<Dim>));
        #endif
};

该类用于向维度系统添加维度。

typedef unit<pressure_dimension,si::system>      pressure;

在这种情况下,“启用”服务的目的是什么?

1 个答案:

答案 0 :(得分:5)

该课程模板为forward declared in "units_fwd.hpp"

template<class Dim,class System, class Enable=void> class unit;

我们看到第3个参数默认为void。我很想做template<class Dim,class System, class=void> class unit;并在实现中保持无名,但可能存在编译器兼容性或代码标准,这意味着它们将其命名为Enable

这种“额外”类型允许对前两种类型进行SFINAE测试。如果您创建一个专门化,其中第三种类型仅对DimSystem的某些子集有效,则额外参数(默认为void)可让您这样做。

您甚至可以将基本实现保留为空(;{};具有不同的效果)并且只进行专门化,使得未通过测试的参数被视为无效选项。

以下是SFINAE的玩具示例:

template<class T, class=void> struct is_int : std::false_type {};
template<class T> struct is_int< T,
  std::enable_if_t< std::is_same<T, int>{} >
> : std::true_type {};

基础专业化继承自false_type。但是,如果类型T在下一个专门化中通过了我的测试,则首选,结果将继承自true_type

在这种情况下,只需执行is_int< int, void >:std::true_type{}即可获得更好的服务,但在更复杂的情况下(例如is_integral),我们可以进行几乎任意的编译时检查并使用它启用或禁用true_type专业化。