以下代码不使用gcc编译,但使用Visual Studio编译:
template <typename T> class A {
public:
T foo;
};
template <typename T> class B: public A <T> {
public:
void bar() { cout << foo << endl; }
};
Run Code Online (Sandbox Code Playgroud)
我收到错误:
test.cpp:在成员函数'void B :: bar()'中:
test.cpp:11:错误:在此范围内未声明'foo'
但它应该是!如果我换bar到
void bar() { cout << this->foo << endl; }
Run Code Online (Sandbox Code Playgroud)
然后它确实编译,但我不认为我必须这样做.GCC在这里遵循C++官方规范中的某些内容,还是仅仅是一个怪癖?
此代码使用MSVC 2015进行编译,但不使用Clang 5.0.0(主干304874)进行编译:
template <typename T>
struct Base
{
T data;
};
template <typename T>
struct Derived : Base<T>
{
auto getData() const
{
return data;
}
};
Run Code Online (Sandbox Code Playgroud)
data用this->datain 替换Derived::getdata()让Clang高兴.
根据C++标准,哪个编译器是正确的?
必须this->在模板代码中使用才能访问基类的标识符?
当模板公开继承自另一个模板时,不是应该可访问的基本公共方法吗?
template <int a>
class Test {
public:
Test() {}
int MyMethod1() { return a; }
};
template <int b>
class Another : public Test<b>
{
public:
Another() {}
void MyMethod2() {
MyMethod1();
}
};
int main()
{
Another<5> a;
a.MyMethod1();
a.MyMethod2();
}
Run Code Online (Sandbox Code Playgroud)
好吧,海湾合作委员会对此嗤之以鼻......我必须遗漏一些完全明显的东西(大脑融化).救命?
经过我们的朋友谷歌搜索后,我无法得到以下观点.
我习惯称之为班级成员this->.即使不需要,我发现它更明确,因为它有助于维护一些带有大量变量的重型算法.
当我正在研究一个应该优化的算法时,我想知道使用是否 this->会改变运行时性能.
可以 ?
从问题:
答案表明 - >可以使用
...在模板中,为了强制后面的符号依赖于后一种用途,它通常是不可避免的.
这意味着什么是这个用途的好例子是什么意思?在这种情况下,我并不完全"依赖"意味着什么,但这听起来像是一个有用的技巧.
如果我使用课程,一切都很好:
struct Base1 {
int value;
Base1(int value) : value(value) { }
};
struct Test1 : public Base1 {
int getValue() { return value; }
Test1(int value) : Base1(value) { }
};
Run Code Online (Sandbox Code Playgroud)
但是需要模板范围解析:
template <typename T>
struct Base {
T value;
Base(T value) : value(value) { }
};
template <typename T>
struct Test : public Base<T> {
typedef Base<T> parent;
T getValue() { return parent::value; } // why do I need to use parent:: here?
Test(T value) : parent(value) { …Run Code Online (Sandbox Code Playgroud) c++ ×6
templates ×5
inheritance ×3
name-lookup ×2
base-class ×1
oop ×1
optimization ×1
this ×1