问题
Let's say I want to have 2 meta functions named 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. How can make this code working?
回答1:
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!
来源:https://stackoverflow.com/questions/35130509/metafunction-overload-c-enable-if