模板函数我有一个模板函数:传递按引用`为const char *`专业化
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.");
但我无法弄清楚如何制定模板,以便模板类型de管道获得文字int
和const 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) { ... }
它的工作原理,但当然,现在我得到呼叫值语义,要求我用的模板参数有一个拷贝构造函数的任何类类型。
有没有办法编写通过引用模板功能与const char *
专业化的作品?
[FYI]字符串文字的类型为“const char [n]'而不是'const char *'。 – NathanOliver
任何理由更喜欢'template <> void foo(int const&t)'over'template <> void foo (int t)'?我宁愿通过值原始类型传递 –
Danh