相关疑难解决方法(0)

我必须在何处以及为何要使用"模板"和"typename"关键字?

在模板,在那里,为什么我必须把typenametemplate上依赖的名字呢?究竟什么是依赖名称?我有以下代码:

template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
    // ...
    template<typename U> struct inUnion {
        // Q: where to add typename/template here?
        typedef Tail::inUnion<U> dummy; 
    };
    template< > struct inUnion<T> {
    };
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
    // ...
    template<typename U> struct inUnion {
        char fail[ -2 + (sizeof(U)%2) ]; // Cannot be instantiated for any …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++-faq dependent-name typename

1061
推荐指数
8
解决办法
15万
查看次数

为什么不允许在非推导的上下文中使用基类定义,以及如何解决这个问题?

我有以下代码:

#include <iostream>

template <typename T>
struct Base
{
    using Type = int;
};

template <typename T>
struct Derived : Base<T>
{
    //uncommmenting the below cause compiler error
    //using Alias = Type;
};

int main()
{
    Derived<void>::Type b = 1;
    std::cout << b << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在Type,Derived如果它在推导的上下文中,则可以使用typename - 如完全有效的声明所示b.但是,如果我尝试Type在其Derived自身的声明中引用,那么我得到一个编译器错误告诉我Type没有命名类型(例如,如果Alias取消注释的定义).

我想这与编译器Type在解析Derived参数的特定实例化的上下文之外的定义时无法检查是否可以从基类中引入时有关T.在这种情况下,这是令人沮丧的,因为Base 总是定义Type不论T.所以我的问题是双重的:

1).为什么地球会发生这种情况?通过这个我的意思是为什么编译器 …

c++ templates struct

10
推荐指数
1
解决办法
796
查看次数

为什么"typedef"这个词在依赖类型之后需要"typename"?

依赖类型通常需要typename告诉编译器成员是一个类型,而不是函数或变量.

但是,情况并非总是如此.
例如,基类不需要这样,因为它只能是一个类型:

template<class T> struct identity { typedef T type; }
template<class T> class Vector : identity<vector<T> >::type { };  // no typename
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,为什么typedef要求typename呢?

template<class T> class Vector
{
    typedef typename /* <-- why do we need this? */ vector<T>::iterator iterator;
};
Run Code Online (Sandbox Code Playgroud)

c++ typedef typename

8
推荐指数
1
解决办法
314
查看次数

标签 统计

c++ ×3

templates ×2

typename ×2

c++-faq ×1

dependent-name ×1

struct ×1

typedef ×1