元函数重载 C++ - enable_if

metafunction overload C++ - enable_if

假设我想要 2 个名为 multiplicate 的元函数。这些元函数应该在矢量类型上运行。

我想要编译的代码:

template <int V1, int V2, int V3...>
struct vector_c{
    enum{
        v1 = V1,
        v2 = V2,
        v3 = V3,
        ///
    };
};

template <typename Vector1, typename Vector2>
struct multiplicate{
   typedef /* do stuff */ type; 
};

template <typename Vector1, int value>
struct multiplicate{
    typedef /* do stuff */ type;
};

问题是,这段代码无法编译。我想做一些事情:

template <typename Vector1, typename Vector2,
    typename enable_if_c<is_vector<Vector2>::value, int>::type =0>
    struct multiplicate{
       typedef /* do stuff */ type; 
    }; //should be fine

template <typename Vector1, int value,
    typename enable_if_c // what now? >
 struct multiplicate{
     //stuff
 };

问题是,在第二种情况下,我不能向 enable_if 添加任何内容,因为 value 不是类型,但它已经是 int 类型的值。如何使此代码正常工作?

您需要使用模板专业化,而不是两个不同的模板。

//Primary template forward declaration
template<typename Vector1, typename Vector2, typename Enable = void>
struct multiplicate;

//specialization when is_vector<Vector2> is true
//leave second argument of enable_if with default value!!!
template<typename Vector1, typename Vector2>
struct multiplicate<Vector1, Vector2,
    typename enable_if<is_vector<Vector2>::value>::type>
{ //do the stuf
};

//specialization when Vector2 is exactly type int
template<typename Vector1, typename Vector2>
struct multiplicate<Vector1, Vector2,
    typename enable_if<is_same<Vector2, int>::value>::type>
{ //do the stuf
};

/* Declaration for any other case! 
   when you comment it (or delete), compilation fails 
   for other types of Vector2 with error: incomplete type */
template<typename Vector1, typename Vector2, typename Enable>
struct multiplicate
{ //do the stuf
};

编码愉快!