具有 const char * 专业化的按引用传递模板函数

Pass-by-reference template functions with `const char *` specialisation

我有一个模板函数:

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<char [14]>(char const [14] &)。我试过像这样重铸模板:

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

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

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

有没有办法编写具有 const char * 专业化的引用传递模板函数?

这个:

foo("Hello, world.");

不打电话给 foo<const char*>。它调用 foo<char[14]>,因为 foo 需要一个 T const&。未调用您的专业化,因为它与模板的类型不同。

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

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

void foo(int const& );

void foo(char const* );

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