【问题标题】:Pass-by-reference template functions with `const char *` specialisation具有 `const char *` 特化的传递引用模板函数
【发布时间】:2016-08-03 15:21:55
【问题描述】:

我有一个模板函数:

template<typename T>
void foo(T const & t);

以及该功能的一些特化:

template<> void foo<int>(int const & t) {
  cout << t << endl;
}

template<> void foo<const char *>(const char * const & t) {
  cout << t << endl;
}

还有一些我想调用该函数的方法:

foo(3);
foo("Hello, world.");

但我不知道如何制定模板,以便模板类型推导得到intconst char * 的文字。如果我执行上述操作,那么我会得到undefined reference to void foo&lt;char [14]&gt;(char const [14] &amp;)。我尝试像这样重铸模板:

template<typename T>
void foo(T t);

template<> void foo<int>(int t) { ... }
template<> void foo<const char *>(const char * t) { ... }

这可行,但当然现在我得到了按值调用的语义,要求我用作模板参数的任何类类型都有一个复制构造函数。

有没有办法编写一个有效的const char * 特化的传递引用模板函数?

【问题讨论】:

  • [FYI] 字符串文字的类型为 const char[n] 而不是 const char *
  • 有什么理由更喜欢template&lt;&gt; void foo&lt;int&gt;(int const &amp; t) 而不是template&lt;&gt; void foo&lt;int&gt;(int t)?我更喜欢按值原始类型传递

标签: c++ templates template-specialization


【解决方案1】:

这个:

foo("Hello, world.");

不调用foo&lt;const char*&gt;。它调用foo&lt;char[14]&gt;,因为foo 需要T const&amp;。未调用您的专业化,因为它与模板的类型不同。

也就是说,不要专攻。重载:

template<typename T>
void foo(T const& );

void foo(int const& );

void foo(char const* );

它更容易推理,更有可能做你真正想做的事。

【讨论】:

  • 当然。在混音中添加重载是我所缺少的。谢谢。
  • 我明白了第一点 - 只是不知道如何获得我想要的效果。
猜你喜欢
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多