相关疑难解决方法(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万
查看次数

C++ 11中依赖类型的模板关键字

这是一个更深入的后续问题: 这个问题

请考虑以下代码:

template <typename T>
class A {
 public:
  template <typename T2>
  const T2* DoSomething() { ... }
};

template <typename T>
class B : public A<T> {
 public:
  const int* DoSomethingElse() {
    return this->DoSomething<int>();  // Compiler wants 'template' keyword here:
 // return this->template DoSomething<int>();
  }
};
Run Code Online (Sandbox Code Playgroud)

为什么不编译?我理解标准的相关部分是14.2/4,但我不确定我理解为什么这不起作用的细节.有人可以打破该部分的措辞来解释为什么这不起作用?另外,您能否(通常)描述在什么情况下可以省略模板关键字?

请注意,在C++ 11下面的代码不会编译:

template <typename T>
class A {
 public:
  template <typename T2>
  const T2* DoSomething() { ... }
};

class B {
 public:
  scoped_ptr<A<int>> var_;

  const int* …
Run Code Online (Sandbox Code Playgroud)

c++ templates

5
推荐指数
1
解决办法
784
查看次数

标签 统计

c++ ×2

templates ×2

c++-faq ×1

dependent-name ×1

typename ×1