English 中文(简体)
操作员超载和模板专业化
原标题:operator overloading and template specialization

我有一个模板类 template< typename T, typename R> . R是类型 victor< Tgt; list< Tgt;

我希望我的班级超载 < < 运算符,这样,如果它是矢量,我将使用在 < < 运算符中建造的操作员来提高效率,如果有列表,我将使用迭代器执行它。

对我来说,这听起来像一个工作 模板专业化 所以我想写这样的东西:

template<typename T, typename R>
T& tContainer_t<T, R>::operator[]( unsigned i )
{
    //TODO with iterators   
}

template<>
T& tContainer_t::operator[]<T, std::vector<T*> >( unsigned i )
{
    // TODO with built in [] operator
}

这是错误的, 而编译者不允许这样做 。

是否有办法让它发挥作用,或者我是否应当使用 typeid () 来区分运行时的两个对象并据此行事?

最佳回答

使用模板的方式是,在一个可以部分专门化的类别中,使静态助手功能成为静态助手。 然而,我要做的是:

template<typename T, typename R>
T& tContainer_t<T, R>::operator[]( unsigned i )
{
    //assuming that the container refernce is name container;
    typename R::iterator itr = container.begin();
    std::advance(itr, i);
    return *itr;
}

std:::advance 得到保证,对于有随机存取迭代器(如矢量)的容器来说,它是固定的时间(基本上,它是迭代器+ n),它可以和在指针上查找矢量时一样快。否则,它会做 terator@/code> n times, 这将是线性时间。 康斯特版本将使用 const_ diator, 但基本上相同 。

这样做将使你能够适当地处理不同类型的集装箱(不仅仅是病媒和清单),而不必修改编码。

问题回答

您不必超载操作员。 图书馆线索包含超载功能来帮助您 。 std:: advance 将会移动一个迭代器, 利用 < code> operator+ () 来随机访问迭代器 。

template<typename T, typename R>
T& tContainer_t<T, R>::operator[]( unsigned i )     
{
    typename R::iterator it = myContainer.begin();
    std::advance(it, i);

    return *it;
} 




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?