简体   繁体   English

元函数重载C ++-enable_if

[英]metafunction overload C++ - enable_if

Let's say I want to have 2 meta functions named multiplicate. 假设我想有2个名为multiplicate的元函数。 Those metafunctions should operate on vector types. 这些元功能应在矢量类型上运行。

  • One metafunction should take as input two vectors and multiply one value by another 一个元函数应将两个向量作为输入,并将一个值乘以另一个

  • Another one should take as input one vector and scalar and multiply all values in vector by scalar. 另一个应将一个向量和标量作为输入,并将向量中的所有值乘以标量。

The code I would like to have compilabe: 我想编译的代码:

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;
};

The thing is, that this code won't compile. 关键是,该代码无法编译。 I thought of doing somehing like: 我想到做这样的事情:

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
 };

The thing is, that in the second case I cannot put anything to enable_if, as value is not a type but it's already a value of type int. 事实是,在第二种情况下,我无法在enable_if中放置任何内容,因为value不是类型,但它已经是int类型的值。 How can make this code working? 如何使此代码起作用?

You need to use template specialization, not two different templates. 您需要使用模板专业化,而不是两个不同的模板。

//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
};

Happy coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM