【发布时间】:2015-04-21 09:01:13
【问题描述】:
#include <iostream>
struct Cls{double dval = 0;};
template<typename T>
void foo(T&& Obj) {
//..... use Obj
}
void foo(const Cls& Obj) {
//..... use Obj.dval
}
//void foo(Cls Obj) {
// //..... use Obj.dval
//}
int main()
{
Cls Obj;
const Cls cv_Obj;
foo(Obj); //case 1
foo(Cls{}); //case 2
foo(cv_Obj); //case 3
foo(10.10);
}
如果函数参数为 const ref 但 by val 适用于所有情况,则 Cls 的模板特化失败 (case 1, case 2)。
除了pass by val,还有其他方法可以处理所有cases(所有值类型)的特化吗?
【问题讨论】:
-
您的模板版本中的行肯定应该是
std::cout<<Obj.dval;而不是std::cout<<Obj; -
下划线开头的标识符保留在全局命名空间中。
-
fails是什么意思?你看到了什么错误? -
我想用
foo打印double, int, etc...,所以模板必须是std::cout<<Obj;错误:除了foo(cv_Obj);,调用了void foo(T&& Obj)函数。error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and '_struct') -
也与 const-default 构造函数问题有关 stackoverflow.com/questions/26077807/…
标签: c++ templates template-specialization