如何在子类中使用嵌套类型的模板基类?

huangapple go评论141阅读模式
英文:

How to use nested type of template base class in sub class?

问题

我有这样的代码:

template <typename T>
struct bar
{
typedef T type;
};

template <typename T>
struct sub_bar : bar<T>
{
typename bar<T>::type x;
};

我知道这是推荐的方式,但我想要像这样编写代码:

template<typename T>
struct sub_bar : bar<T>
{
...

    type x;

};


如何做到呢?我认为我可以像这样做:

template<typename T>
struct sub_bar : bar<T>
{
typedef typename bar<T>::type type;

    type x;

};


类型是什么可能会有歧义吗?不过这段代码在gcc9编译器下工作。
英文:

I have code like this:

template &lt;typename T&gt;
struct bar
{
        typedef T type;
};

template &lt;typename T&gt;
struct sub_bar : bar&lt;T&gt;
{
        typename bar&lt;T&gt;::type x;
};

I know that this is recommended way, but I want write code like this:

template&lt;typename T&gt;

struct sub_bar : bar&lt;T&gt;

{
        ...

        type x;

};

How to do it? I think I can do something like this:


template&lt;typename T&gt;

struct sub_bar : bar&lt;T&gt;

{
        typedef typename bar&lt;T&gt;::type type;

        type x;

};

Is it ambiguous what's type? However this code works with gcc9 compiler.

答案1

得分: 3

我倾向于使用一个强制合格查找并写入的小技巧

using typename sub_bar::type;

来避免重复基类的模板参数(并避免在一个奇怪的情况下,两个类都被搜索到 type 时可能出现的歧义),但你写的方式确实有效。

英文:

I would tend to use a trick of forcing qualified lookup and write

using typename sub_bar::type;

to avoid repeating the template arguments of the base class (and to avoid potential ambiguity in a strange situation where both classes were searched for type), but what you wrote definitely works.

huangapple
  • 本文由 发表于 2023年8月5日 13:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定