【发布时间】: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.");
但我不知道如何制定模板,以便模板类型推导得到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 *。 -
有什么理由更喜欢
template<> void foo<int>(int const & t)而不是template<> void foo<int>(int t)?我更喜欢按值原始类型传递
标签: c++ templates template-specialization