English 中文(简体)
c++ 功能规范化
原标题:c++ function code generalization using template

我写的是具有以下职能的类似集装箱类别:

    Iterator begin(){
        return Iterator(data_.begin(), 1);
    }

    ConstIterator begin() const{
        return ConstIterator(data_.begin(), 1);
    }

我认为,我可以发挥一项职能,以取代:

    template <typename itr0, typename itr1>
    itr0 begin(){
        return itr1(data_.begin(), 1);
    }

并且当我称之为“以下”时,该守则是在汇编时间时产生的:

    Iterator it = foo.begin<Iterator, Iterator>();
    ConstIterator it = foo.begin<ConstIterator const?, ConstIterator>();

我的第一个问题是,究竟是什么类型的名称?

其次,这是否有助于使这种美术在课外透明? i.e. 我仍可使用以下代码,以标准方式写成。

    C foo;
    const C foo2;
    Iterator it = foo.begin();
    ConstIterator it = foo2.begin();
最佳回答

不幸的是,你需要分别界定这两种方法,因为正如你所指出的,它们的签名因<条码>而异。 没有可以克服的模版 w药(至少我不知道)。

然而,你可以使用一些不同的技术,将其实施合并成一种单一的方法。 此处为避免需要<代码>const_cast<>/code>的下列选择:

struct Container
{
    template< typename I, typename C >
    friend I begin_impl( C & c ){
      return I( c.data_.begin(), 1 );
    }

    Iterator begin(){
        return begin_impl< Iterator >( *this ); // *this is "Container"
    }

    ConstIterator begin() const{
        return begin_impl< ConstIterator >( *this ); // *this is "Container const"
    }
};

See here

问题回答

暂无回答




相关问题
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?

热门标签