C++ Function Template, Int Parameter Question
I was curious why this doesn't work:
const int ASSIGN_LEFT = 1;
const int ASSIGN_RIGHT = 2;
template <int AssignDirection>
void map( int& value1, int& value2 );
template<>
void map<ASSIGN_LEFT>( int& value1, int& value2 )
{ value1 = value2; }
template<>
void map<ASSIGN_RIGHT>( int& value1, int& value2 )
{ value2 = value1; }
When I try to use this function, it calls whichever template specialization I defined first. So, map<ASSIGN_RIGHT>
will call map<ASSIGN_LEFT>
in the code above, unless I flip the order of the specialization, then it will always call map<ASSIGN_RIGHT>
.
int main()
{
int dog = 3;
int cat = 4;
map<ASSIGN_RIGHT>( dog, cat );
std::cout << "dog= " << dog << ", cat= " << cat << std::endl;
}
Output is
dog= 4, cat= 4
The idea of this is so I don't have to write two routines to input/output data from a structure.
Auxiliary question -- I开发者_JAVA百科'd like to make the "int"s above a template parameter, but obviously you cannot do a partial specialization. Would love to find a way around that.
Thanks in advance.
The following definitely works. It also works around the fact that you can't partially specialize a function template by having the function template delegate to a specialized class template:
enum AssignDirection { AssignLeft, AssignRight };
template <typename T, AssignDirection D>
struct map_impl;
template <typename T>
struct map_impl<T, AssignLeft>
{
static void map(T& x, T& y) { x = y; }
};
template <typename T>
struct map_impl<T, AssignRight>
{
static void map(T& x, T& y) { y = x; }
};
// Only template parameter D needs an explicit argument. T can be deduced.
template <AssignDirection D, typename T>
void map(T& x, T& y)
{
return map_impl<T, D>::map(x, y);
}
精彩评论