简体   繁体   English

C ++模板和访问命名空间

[英]C++ Templates and accessing namespaces

Let's say I'm using a templated class with something simple like: 假设我正在使用模板化的类,其中包含以下内容:

template <class T> 
class MyClass

I want to use elements from T's namespace, for example T could be string, and I wanted to use 我想使用T的命名空间中的元素,例如T可以是字符串,我想使用

T::const_iterator myIterator; 

...or something like that. ...或类似的东西。 How do I achieve that? 我如何实现这一目标? Probably, it's either not possible or very simple, but I have no idea. 可能,它要么不可能,要么非常简单,但我不知道。

Thanks for answers! 谢谢你的回答!

By default if T is a template parameter like in your example, the T::some_member is assumed not to name a type. 默认情况下,如果T是模板参数(如示例中所示),则假定T::some_member不命名类型。 You have to explicitly specify that it is, by prefixing it with typename : 您必须通过在其前面添加typename来明确指定它:

typename T::const_iterator myIterator;

This resolves some parsing problems like in the following example 这解决了一些解析问题,如下例所示

// multiplication, or declaration of a pointer?
T::const_iterator * myIterator;

So that the compiler can parse this even before instantiating the template, you have to give it a hand and use typename , including in those cases where it wouldn't be ambiguous, like in the first case above. 因此编译器甚至可以在实例化模板之前对其进行解析,您必须手动使用typename ,包括那些不会模糊的情况,就像上面的第一种情况一样。 The Template FAQ has more insight into this. 模板常见问题解答对此有更深入的了解。

It is definitely possible. 这绝对是可能的。

template< typename T >
class Example
{
    void foo( const T& t )
    {
        typedef typename T::value_type Type;
        typedef typename T::const_iterator Iter;
        Iter begin = t.begin();
        Iter end = t.end();

        std::copy( begin, end, std::ostream_iterator<Type>(std::cout) );
    }
};

The key is the typename part of the typedef. 关键是typedef的typename部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM