当涉及依赖范围的内部类时,如何使C ++找到模板函数头? [英] How to make C++ find templated function header when dependent-scoped inner classes are involved?

查看:179
本文介绍了当涉及依赖范围的内部类时,如何使C ++找到模板函数头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a templated C++ function that accepts, as its argument, a pointer to an object of an inner class. Here is a reduced version of the class structure involved, similar to a typical linked-list or tree class:

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

  Inner* ptr;

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



我已经使他们的结构排除任何访问控制问题,并删除了一些额外的实例变量。考虑到这个类结构,这里有三个函数,前两个函数不是我想要的:

I've made them structs to exclude any access control issues and removed some extraneous instance variables. With that class structure in mind, here are three functions, the first two of which aren't quite what I want:

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;
}

这第三个函数基本上是我想要的,一个帮助函数在一个更大的代码体,当然),但它不工作。如果我编译并运行以下主函数:

This third function is basically what I want, header-wise (it's intended as a helper function in a larger body of code, of course), but it doesn't work. If I compile and run the following main function:

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

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

它运行正常(打印 5 三次),但如果我取消注释的行调用 testInnerTemplated ,我得到一个编译器错误,说明没有匹配的函数调用到'testInnerTemplated(Outer< int> :: Inner *&)'(在g ++ 4.9.1中)。我想这是模板查找或匹配的问题,但我怎么能告诉编译器如何解决它?

it runs just fine (printing 5 three times), but if I uncomment the line with the call to testInnerTemplated, I get a compiler error saying no matching function for call to ‘testInnerTemplated(Outer<int>::Inner*&)’ (in g++ 4.9.1). I guess it's a problem with the template lookup or matching, but how can I tell the compiler how to resolve it?

推荐答案

您希望从内部中的外部<> 恢复类型信息,您可以使用traits。

If you wish to recover the type information from Outer<> from within Inner, you can use traits.

template <typename T>
struct Outer
{
    typedef T TypeParam;

    struct Inner
    {
        typedef Outer<T> InnerOuter;
        T val;
        Inner (T v) : val(v) {}
    };

    Inner *ptr;

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

现在定义一个更通用的 testInnerTemplated 它使用traits来恢复传递给外部<> 的类型信息。

Now define a more generic testInnerTemplated, but it uses traits to recover the type information passed to Outer<>.

template <typename T>
void testInnerTemplated (const T * p)
{
  typename T::InnerOuter::TypeParam val = p->val;
  std::cout << val << std::endl;
}

这篇关于当涉及依赖范围的内部类时,如何使C ++找到模板函数头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆