Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I port msvc++ code with non-dependent names in templates to Linux?

Tags:

c++

templates

I can deal with porting platform dependent functions. I have a problem that the compilers I tried on Linux (clang and g++) do not accept the following code, while the msvc++ compiler does:

template <class T>
class Base {
protected:
    T Value;
};

template <class T>
class Derived : public Base<T> {
public:
    void setValue(const T& inValue){
        Value = inValue;
    }
};

int main(int argc, char const *argv[])
{
    Derived<int> tmp;
    tmp.setValue(0);
    return 0;
}

g++ error:

main.cpp: In member function ‘void Derived<T>::setValue(const T&)’:
main.cpp:11:3: error: ‘Value’ was not declared in this scope

I believe this due to the use of a non-dependent name (Value) in the second class. More information.

The problem is that I have a very large code base, in which this type of code is used very often. I understand that it is wrong when looking at the standard. However it is very convenient not having to write this-> or Base<T>:: in front of every use of Value. Even writing using Base<T>::Value; at the start of the derived class is problematic when you use ~20 members of the base class.

So my question is: are there compilers for Linux that allow this kind of code (with or without extra compiler switches)? Or are there small modifications that will allow this code to compile on Linux?

like image 577
user362382 Avatar asked Dec 26 '22 15:12

user362382


1 Answers

You have to say this->Value or Base<T>::Value, because Value is a dependent name. Alter­natively, add using Base<T>::Value; to your derived class definition. There's no way around this.

The Microsoft compiler was simply sub-standard, and it is your misfortune to have coded to a vendor's style and not to the published C++ standard, I'm afraid.

like image 183
Kerrek SB Avatar answered Mar 22 '23 22:03

Kerrek SB