CLion does not correctly handle superclass members with templates
I have found a code structure that CLion handles incorrectly with regards to the C++11 spec. I was not able to find an existing issue that demonstrates this problem, but perhaps it is related to another issue of which I am not aware.
This code fails to compile, while CLion shows no code analysis errors:
#include <iostream>
template <typename T>
struct Parent {
Parent(T var) : someVar(var) {}
T someVar;
};
template <typename T>
struct Child : Parent<T> {
Child(T var) : Parent<T>(var) {}
T getVar() {
return someVar;
}
};
int main() {
Child<int> child(10);
std::cout << child.getVar() << "\n";
}
Cygwin toolchain produces the following error:
/cygdrive/e/repository/untitled1/main.cpp:13:16: error: 'someVar' was not declared in this scope
return someVar;
^~~~~~~
The following code compiles, but not in the way CLion interprets it.
CLion thinks someVar on line 15 (previously line 13) refers to Parent::someVar, while the compiler sees it as the global variable on line 3.
#include <iostream>
int someVar = 420;
template <typename T>
struct Parent {
Parent(T var) : someVar(var) {}
T someVar;
};
template <typename T>
struct Child : Parent<T> {
Child(T var) : Parent<T>(var) {}
T getVar() {
return someVar;
}
};
int main() {
Child<int> child(10);
std::cout << child.getVar() << "\n";
}
prints 420 instead of 10
For reference, this is what the code should look like (line 13: 'this->'):
#include <iostream>
template <typename T>
struct Parent {
Parent(T var) : someVar(var) {}
T someVar;
};
template <typename T>
struct Child : Parent<T> {
Child(T var) : Parent<T>(var) {}
T getVar() {
return this->someVar;
}
};
int main() {
Child<int> child(10);
std::cout << child.getVar() << "\n";
}
This StackOverflow answer helped me solve my issue: https://stackoverflow.com/a/4010291/1806348
请先登录再写评论。
I've just updated to 2018.1.2 and I can confirm this issue still persists in this version.
However, I have also since noticed that Microsoft's C++ compiler MSVC does compile the incorrect code successfully according how CLion interprets the code (I realize this compiler is not officially supported yet). Perhaps it would be necessary to make CLions understanding of the code adapt to the toolchains used?