元函数重载 C++ - enable_if

metafunction overload C++ - enable_if

本文关键字:enable if C++ 函数 重载      更新时间:2023-10-16

假设我想有 2 个名为乘法的元函数。这些元函数应该对向量类型进行操作。

    一个
  • 元函数应将两个向量作为输入,并将一个值乘以另一个值

  • 另一个应该将一个向量和标量作为输入,并将向量中的所有值乘以标量。

我想编译的代码:

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,因为值不是一个类型,但它已经是 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
};

祝您编码愉快!