我不知道为什么这些代码无法编译.我在Visual c + + 2010和gcc中测试了-std = c ++ 0x.有人提出一些建议吗?谢谢!
template<typename T>
class Foo
{
public:
void test(const T&){cout<<"const";}
void test( T&){cout<<"non const";}
};
int main()
{
int a;
Foo<int&> f;
}
Run Code Online (Sandbox Code Playgroud)
编译错误:'void Foo :: test(T)':已定义或声明的成员函数
但为什么这可以编译?
template<typename T> void foo(const T&){cout<<"const"; }
template<typename T> void foo( T&){cout<<"non const"; }
int main()
{
int a;
foo<int&>(a);
}
Run Code Online (Sandbox Code Playgroud)
我读过c ++ 0x文章说:T && == T&,所以const T && == const T&?
sel*_*tze 13
我读过c ++ 0x文章说:T && == T&,所以const T && == const T&?
实际上,这并没有多大意义.恕我直言,最好把它放到一张桌子里:
T T& const T const T&
---------------------------------------
int int& const int const int&
int& int& int& int&
(1) (2) (1+2)
1: Reference collapsing in action
2: const applies to the reference and is therefore ignored
Run Code Online (Sandbox Code Playgroud)
如果T已经是引用(第2行),则const const T适用于引用而不适用于裁判.但是,在初始化之后你无法使它引用另一个对象的意义上,引用本质上是不变的,所以const在这里忽略a .你可以把它想象成"const崩溃".;-)
这个:
Foo<int&> f;
Run Code Online (Sandbox Code Playgroud)
引起这种实例化:
class Foo<int&>
{
public:
void test(int&);
void test(int&);
};
Run Code Online (Sandbox Code Playgroud)
const应用于作为参考的类型是无操作.将它与在参考数据成员上运行的非静态成员函数进行比较:
struct A {
int &ref;
// valid: const member function doesn't treat "ref" as "const int&".
void operate() const {
ref = 0;
}
};
Run Code Online (Sandbox Code Playgroud)
你必须通过int以Foo<...>实现自己的目标.
| 归档时间: |
|
| 查看次数: |
845 次 |
| 最近记录: |