草庐IT

c++模板函数参数推导和函数解析

coder 2024-02-18 原文

今天我只是想提出一个关于C++ 11(我使用的是vs2010 sp1)中的C++模板函数参数推导和模板函数重载解析的问题。 我定义了两个模板函数如下:

函数#1:

template <class T>
void func(const T& arg)
{
    cout << "void func(const T&)" <<endl;
}

函数#2:

template <class T>
void func(T&& arg)
{
   cout << "void func(T&&)" <<endl;
}

现在考虑以下代码:

int main() {
    //I understand these first two examples:

    //function #2 is selected, with T deduced as int&
    //If I comment out function #2, function#1 is selected with
    //T deduced as int
    {int a = 0; func(a);}

    //function #1 is selected, with T is deduced as int.
    //If I comment out function #1, function #2 is selected,
    //with T deduced as const int&.
    {const int a = 0; func(a);}

    //I don't understand the following examples:  

    //Function #2 is selected... why?
    //Why not function #1 or ambiguous...
    {func(0);}

    //But here function #1 is selected.
    //I know the literal string “feng” is lvalue expression and
    //T is deduced as “const char[5]”. The const modifier is part
    //of the T type not the const modifier in “const T&” declaration. 
    {func(“feng”)}

    //Here function#2 is selected in which T is deduced as char(&)[5]
    {char array[] = “feng”; func(array);}
}

我只想知道在这些场景下指导函数重载决策背后的规则。

我不同意下面的两个答案。我认为 const int 示例与文字字符串示例不同。我可以稍微修改一下#function 1 看看推导的类型到底是什么

 template <class T>
 void func(const T& arg)
 {
    T local;
    local = 0;
    cout << "void func(const T&)" <<endl;
 }
 //the compiler compiles the code happily 
 //and it justify that the T is deduced as int type
 const int a = 0;
 func(a);

 template <class T>
 void func(const T& arg)
 {
T local;
Local[0] = ‘a’;
cout << "void func(const T&)" <<endl;
 }
 //The compiler complains that “error C2734: 'local' : const object must be     
 //initialized if not extern
 //see reference to function template instantiation 
 //'void func<const char[5]>(T (&))' being compiled
  //    with
  //    [
  //        T=const char [5]
  //    ]

 Func(“feng”);

在 const int 示例中,“const T&”声明中的 const 修饰符吞噬了 const int 的“constness”;而在文字字符串示例中,我不知道“const T&”声明中的 const 修饰符在哪里。声明一些像int& const是没有意义的(但是声明int* const是有意义的)

最佳答案

这里的技巧是 const。 F1 和 F2 都可以接受任何类型的任何值,但 F2 通常是更好的匹配,因为它是完美转发。因此除非值是 const 左值,否则 F2 是最佳匹配。然而,当左值为 const 时,F1 是更好的匹配。这就是为什么它更适合 const int 和字符串文字的原因。

关于c++模板函数参数推导和函数解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258608/

有关c++模板函数参数推导和函数解析的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

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

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

  6. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  7. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  10. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

随机推荐