简体   繁体   中英

Template function argument in derived class

I was wondering why below code does not compile with gcc (4.6.3) while it works perfectly fine using cl. I can obviously compile it with gcc by removing the template argument of the DoSomething function. Nonetheless I'd like to understand why the syntax below is not correct.

Thanks for any hints.

template <class T>
class Base {
public:
    template <class B>
    struct Var1 {
        B var1_var;
    };

    Base() {};
    ~Base() {};
    template <class V> void DoSomething(V val) {
        std::cout << val.var1_var << std::endl;
    }
};

template <class T>
class Derived : public Base<T> {
public:
    Derived() {};
    ~Derived() {};
    void Test() {
        typename Base<T>::template Var1<int> val;
        val.var1_var = 5;
        Base<T>::DoSomething<typename Base<T>::template Var1<int> >(val);   //error: expected ‘(’ before ‘>’ token
    }
};

int main(int, char**) {
    Derived<double> bla;
    bla.Test();
    return 0;
}

The problem is that Test is a nondependant name (it does not involve T ) so the compiler won't look in dependant base class while looking for the function Dosomething . You can solve this problem like you did (with 0x499602D2 's answer), but it will not allow virtual dispatch mechanism. You can solve this just by using this->DoSomething(val) also, that will enable virtual dispatch.

More information here .

You need another template :

Base<T>::template DoSomething<typename Base<T>::template Var1<int> >(val);
//       ^^^^^^^^

Update: You also don't need to provide the template parameter. You can allow template argument deduction to do it for you:

DoSomething(val);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM