在模板,在那里,为什么我必须把typename和template上依赖的名字呢?究竟什么是依赖名称?我有以下代码:
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) 我有以下代码:
#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).为什么地球会发生这种情况?通过这个我的意思是为什么编译器 …
依赖类型通常需要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)