使用模板的c ++函数代码泛化 [英] c++ function code generalization using template

查看:140
本文介绍了使用模板的c ++函数代码泛化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个类似stl的容器类,它具有以下功能:

I am writing a stl-like container class which has the following functions:

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

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

我想我可以创建一个函数来替换它们:

I think I could make one function to replace both:

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

当我调用以下代码时,代码在编译时生成:

and when I call the following, the code is generated in compile time:

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

我的第一个问题是,什么typename实际上是 ConstIterator begin()const

My first question is, what typename is actually ConstIterator begin() const?

其次,有没有办法让这个元编程在课堂外是透明的?即我仍然可以使用以下代码调用begin(),就好像它是以标准方式编写的一样?

Secondly, is there a way to make it so that this metaprogramming is transparent from outside of the class? i.e. I could still use the following code to call begin() as if it was written in a standard way?

    C foo;
    const C foo2;
    Iterator it = foo.begin();
    ConstIterator it = foo2.begin();


推荐答案

不幸的是你需要分别定义这两种方法因为,正如您所指出的,它们的签名因 const 修饰符而异。没有可用的模板魔法可以克服这个问题(至少没有我知道的)。

Unfortunately you'll need to define the two methods separately since, as you've noted, their signature differs by the const modifier. There's no template wizardry available that can overcome that (at least none that I'm aware of).

然而,你可以使用许多不同的技术将他们的实现组合到一种方法。这是一个这样的选项,可以避免任何 const_cast 'ing:

You can however use a number of different techniques to combine their implementations into a single method. Here's one such option that avoids the need for any const_cast'ing:

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

参见这里有更多选项。

这篇关于使用模板的c ++函数代码泛化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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