【问题标题】:C++ Function Template, Int Parameter QuestionC++ 函数模板,Int 参数问题
【发布时间】:2011-04-26 03:37:21
【问题描述】:

我很好奇为什么这不起作用:

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

当我尝试使用这个函数时,它会调用我首先定义的模板特化。所以,map&lt;ASSIGN_RIGHT&gt; 将在上面的代码中调用map&lt;ASSIGN_LEFT&gt;,除非我翻转专业化的顺序,否则它将始终调用map&lt;ASSIGN_RIGHT&gt;

int main()
{
   int dog = 3;
   int cat = 4;

   map<ASSIGN_RIGHT>( dog, cat );
   std::cout << "dog= " << dog << ", cat= " << cat << std::endl;
}

输出是

dog= 4, cat= 4

这样做的想法是,我不必编写两个例程来从结构中输入/输出数据。

辅助问题——我想在模板参数上方添加“int”,但显然你不能进行部分特化。很想找到解决办法。

提前致谢。

【问题讨论】:

  • 您能说明一下您是如何调用该函数的吗?
  • 嗯,以上在 VC8 和 VC10 上对我来说很好。
  • @Georg:嗯。我不知道当它在 VC10 中“不起作用”时我在做什么......我用 OP 的 repro 再次尝试了它,它工作正常。

标签: c++ templates function specialization


【解决方案1】:

以下绝对有效。它还解决了您不能通过将函数模板委托给专门的类模板来部分专门化函数模板的事实:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多