派生类中的模板函数参数(Template function argument in derived class)

编程入门 行业动态 更新时间:2024-10-27 08:28:29
派生类中的模板函数参数(Template function argument in derived class)

我想知道为什么下面的代码不能用gcc(4.6.3)编译,而它使用cl工作得很好。 我显然可以通过删除DoSomething函数的模板参数来使用gcc编译它。 尽管如此,我想了解为什么下面的语法不正确。

谢谢你的任何提示。

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; }

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; }

最满意答案

问题是Test是一个nondependant name dependant nondependant name (它不涉及T ),因此编译器在查找函数Dosomething时不会查找dependant基类。 你可以解决这个问题(使用0x499602D2的答案),但它不允许虚拟调度机制。 您只需使用this->DoSomething(val)即可解决此问题,这将启用虚拟调度。

更多信息在这里 。

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.

更多推荐

本文发布于:2023-08-07 14:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464762.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类中   模板   参数   Template

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!