草庐IT

c++ - 编译器如何传递 `std::initializer_list` 值? (或 : how can I get around a universal overload with one? )

coder 2024-02-26 原文

Continuing my saga ,我意识到我可以使用单个 std::initializer_list 参数来重载我的访问函数:

class array_md
{
    //...
    my_type &        operator []( size_type i )
    { /* Lots of code */ }
    my_type const &  operator []( size_type i ) const
    { /* same Lots of code, with "const" sprinkled in */ }
    my_type &        operator []( std::initializer_list<size_type> i )
    { /* Lots of different code */ }
    my_type const &  operator []( std::initializer_list<size_type> i ) const
    { /* same Lots of different code, with "const" sprinkled in */ }
    //...
};

对于我的 at 版本,我现在有:

class array_md
{
    //...
    template < typename ...Index >
    complicated &        at( Index &&...i )  // (1)
    { /* Lots of code */ }
    template < typename ...Index >
    complicated const &  at( Index &&...i ) const  // (2)
    { /* same Lots of code, with "const" sprinkled in */ }
    my_type &            at( std::initializer_list<size_type> i )  // (3)
    { /* Lots of different code */ }
    my_type const &      at( std::initializer_list<size_type> i ) const  // (4)
    { /* same Lots of different code, with "const" sprinkled in */ }
    //...
};

(由于我无法根据初始化列表中的条目数量更改类型,因为它是运行时的,所以我修复了返回类型并在条目数量错误时抛出。) new overloads 很长,我必须为 mutableconst 版本重复它,所以我想知道如何保存代码。我试图搞乱 const_cast:

class array_md
{
    //...
    my_type &        operator []( size_type i );
    my_type const &  operator []( size_type i ) const;
    my_type &        operator []( std::initializer_list<size_type> i )
    {
        return const_cast<my_type &>( const_cast<array_md const
         *>(this)->operator [](i) );
    }
    my_type const &  operator []( std::initializer_list<size_type> i ) const;
    //...
};

此处第三个版本调用第四个版本,使用 const_cast 来绕过编译器投诉。 (侵入是可以的,因为我正在剥离 const 我一开始就打它的东西。不要颠倒依赖关系;你最终可能会调用一个 mutable 成员在真正的 const 对象上运行!)我尝试对 at 做同样的事情,用标记 (4) 的重载实现标记 (3) 的重载。但是,因为 at 有三个替代项,所以我得到了与 (2) getting selected instead 相关的错误!与通用重载相比,我将 std::initializer_list 传递给内部 at 调用(按值)是否存在某些问题不会导致完全匹配?我是 old friends与通用方法冲突。

TL;DR:示例代码显示 std::initializer_list 对象在函数参数列表中被取值。这是编译器传递它们的首选吗?还是通过引用代替?如果您需要精确匹配(以克服通用过载),这一点很重要。

最佳答案

消歧类型转换:

int     f( int );
double  f( double );

template < typename Func, typename ...Args >
void  do_it( Func &&f, Args &&...a );

//...

int  main( int, char *[] )
{
    do_it( (double(*)(double))&f, 5.4 );
    return 0;
}

main 中的代码被迫使用 f 的第二个版本。我认为此功能是 C-cast 所独有的,但它在 static_cast 下。所以我得到了类似的东西:

class array_md
{
    //...
    template < typename ...Index >
    complicated &        at( Index &&...i );  // (1)

    template < typename ...Index >
    complicated const &  at( Index &&...i ) const;  // (2)

    my_type &            at( std::initializer_list<size_type> i )  // (3)
    {
        return const_cast<my_type &>(
          (
            const_cast<array_md const *>( this )
            ->*
            static_cast<
              my_type const &
              (array_md::*)
              ( std::initializer_list<size_type> ) const
            >( &array_md::at )
          )( i )
        );
    }

    my_type const &      at( std::initializer_list<size_type> i ) const;  // (4)
    //...
};

(我的灵感来自于回答别人关于需要区分函数模板重载的帖子。)尝试了几次,尤其是在不必创建中间对象的情况下。

关于c++ - 编译器如何传递 `std::initializer_list` 值? (或 : how can I get around a universal overload with one? ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16272630/

有关c++ - 编译器如何传递 `std::initializer_list` 值? (或 : how can I get around a universal overload with one? )的更多相关文章

  1. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  4. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  9. ruby - 如何将 Puma::Configuration 传递给 Sinatra? - 2

    这是我的网络应用:classFront我是这样开始的(请不要建议使用Rack):Front.start!这是我的Puma配置对象,我不知道如何传递给它:require'puma/configuration'Puma::Configuration.new({log_requests:true,debug:true})说真的,怎么样? 最佳答案 配置与您运行的方式紧密相关puma服务器。运行的标准方式puma-pumaCLI命令。为了配置puma配置文件config/puma.rb或config/puma/.rb应该提供(参见examp

  10. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

随机推荐