英文:
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 <typename T>
struct bar
{
typedef T type;
};
template <typename T>
struct sub_bar : bar<T>
{
typename bar<T>::type x;
};
I know that this is recommended way, but I want write code like this:
template<typename T>
struct sub_bar : bar<T>
{
...
type x;
};
How to do it? I think I can do something like this:
template<typename T>
struct sub_bar : bar<T>
{
typedef typename bar<T>::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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论