我听说过一些关于引用参考问题和this解决方案的内容。我对C ++委员会术语不是很了解,但我理解链接中的“Moved to DR”注释意味着这是符合标准的编译器应该遵守的当前解释。
我有这个我无法理解的示例代码:
template <typename T>
struct C {
void f(T&) { }
void f(const T&) { }
};
int main() {
C<int> x; // OK
C<int&> y; // compile error: f cannot be overloaded
C<const int&> z; // compile error: f cannot be overloaded
}
我理解C<const int&>
案例中的错误:使用DR#106中的规则,我们得到两个具有相同签名f(const int&amp;)的方法。我没有得到的是C<int&>
案例:它不应该生成与C<int>
完全相同的代码(至少根据Stroustrup的决议)?
答案 0 :(得分:3)
DR仅表示“缺陷报告”,据我所知,所描述的解决方案尚未达到标准。因此,我认为严格符合C ++ 03的实现不应该编译此代码,因为它正在形成对引用的引用。
[编辑]刚刚在这个问题上找到nice answer。
答案 1 :(得分:1)
有趣的是,当我编译你的代码(Visual C ++ 10 Express)时,我会遇到错误,但是当我尝试这个更简单的情况时:
int main(int argc, char* argv[])
{
C<int> x; // OK
C<const int> x1; // error C2535: 'void C<T>::f(T &)' : member function
// already defined or declared
return 0;
}
似乎你提到的DR中定义的ref-to-ref折叠意味着const
ref成为模板中的简单非const ref。我的问题是,我不明白为什么第二个f
不会被忽略。
如果我更改C以使第二个f为const
- 合格,则现在编译:
template <typename T>
struct C {
void f(T&) { }
void f(const T& t) const {}
};
暗示似乎是当C
用const
实例化任何(ref或not)时,两个C::f
重载完全相同,并导致编译时重复检测
也许比我更聪明的人可以在这里更明确地解读链条。
编辑:经过反思,这里T = const int&
导致f
重载被同样实例化为
void f(const int&) {}
这就是编译器告诉我的:
#include "stdafx.h"
template <typename T>
struct C {
void f(T&) { }
void f(const T&) { }
};
int main() {
C<const int&> z; // compile error: f cannot be overloaded
return 0;
}
给出了这个错误:
1>test.cpp(6): error C2535: 'void C<T>::f(T)' : member function already
defined or declared
1> with
1> [
1> T=const int &
1> ]
1> test.cpp(5) : see declaration of 'C<T>::f'
1> with
1> [
1> T=const int &
1> ]
1> test.cpp(10) : see reference to class template instantiation
'C<T>' being compiled
1> with
1> [
1> T=const int &
1> ]
我甚至不相信这与DR有任何关系。