在一个带有通用类型T的C++模板中,我可以使用:
const T &
要获取对常量T的引用。但是,如果现在T本身是一个引用类型(例如T = int&),则上述术语解析为
int &
而不是
const int &
这是有道理的,因为任何引用本身都是常量。但是,是否仍有一种方法可以要求一个
const T &
如果 T 本身是一个引用类型?
编辑:用于评估的示例代码(g++编译器):
template <typename T> class TemplateClass
{
public:
void foo(const T &bar) { }
};
int main()
{
TemplateClass<int &> x;
x.foo(0); // <-- compile error: no conversion from int to int&
return 0;
}
int&
。你为什么认为它会这样做? - Mooing Duck