c++ - 当涉及依赖范围的内部类时,如何使 C++ 找到模板化函数头?

标签 c++ templates inner-classes

我正在尝试构建一个模板化的 C++ 函数,它接受一个指向内部类对象的指针作为其参数。这是所涉及的类结构的简化版本,类似于典型的链表或树类:

template <typename T>
struct Outer
{
  struct Inner
  {
    T val;
    Inner (T v) : val(v) { }
  };

  Inner* ptr;

  Outer(T val)
  {
    ptr = new Inner(val);
  }
};

我已经将它们构造为排除任何访问控制问题并删除了一些无关的实例变量。考虑到该类结构,这里有三个函数,其中前两个不是我想要的:

template <typename T>
void testOuter (const Outer<T>& obj)
{
  cout << obj.ptr->val << endl;
}

void testInnerInt (const Outer<int>::Inner* p)
{
  cout << p->val << endl;
}

template <typename T>
void testInnerTemplated (const typename Outer<T>::Inner* p)
{
  cout << p->val << endl;
}

这第三个函数基本上是我想要的,在 header 方面(当然,它旨在作为更大代码体中的辅助函数),但它不起作用。如果我编译并运行以下主要函数:

int main()
{
  Outer<int> foo(5);

  cout << foo.ptr->val << endl;
  testInnerInt(foo.ptr);
  //testInnerTemplated(foo.ptr);
  testOuter(foo);
}

它运行得很好(打印 5 三次),但如果我取消注释调用 testInnerTemplated 的行,我得到一个编译器错误说 no matching function for call to ‘testInnerTemplated(Outer<int>::Inner*&)’ (在 g++ 4.9.1 中)。我猜是模板查找或匹配的问题,但我如何告诉编译器如何解决它?

最佳答案

template <typename T>
void testInnerTemplated(const typename Outer<T>::Inner*);

编译器无法推断T通过模板参数推导,因为这是标准中定义的非推导上下文:

The nondeduced contexts are:

The nested-name-specifier of a type that was specified using a qualified-id. A type that is a template-id in which one or more of the template-arguments is an expression that references a template-parameter.

When a type name is specified in a way that includes a nondeduced context, all of the types that comprise that type name are also nondeduced. However, a compound type can include both deduced and nondeduced types. [Example: If a type is specified as A<T>::B<T2>, both T and T2 are nondeduced. Likewise, if a type is specified as A<I+J>::X<T>, I, J, and T are nondeduced. If a type is specified as void f(typename A<T>::B, A<T>), the T in A<T>::B is nondeduced but the T in A<T> is deduced. ]

关于c++ - 当涉及依赖范围的内部类时,如何使 C++ 找到模板化函数头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942729/

相关文章:

c++ - 如果函数调用是 return 语句,编译器能否自动 move 函数参数?

c++ - 从 C++ 使用 SOCKS 代理

c++ - 无法将 void* 动态转换为模板类

c++ - C/C++ - 覆盖默认函数

c++ - 如何在 C\C++ 中将位图作为帧写入 Ogg Theora?

c++ - 嵌套类的部分特化

angularjs - 如何在 rails slim 模板中添加 Angular 属性指令以输入?

java - 具有实例变量的通用内部类,该实例变量是另一个通用内部类的对象

java - Java 中的静态嵌套类

scala - 不同文件中的内部类