【问题标题】:const char array template vs char const* function overload [duplicate]const char数组模板与char const *函数重载[重复]
【发布时间】:2018-02-02 19:30:22
【问题描述】:

在我写这个问题时,我已经查看了堆栈溢出提出的建议相关问题的所有答案,我已经用谷歌搜索了,我已经查看了STL's video 上的重载解决方案,试图找出是什么导致了以下问题代码在模板上选择char const*重载,但我想不通。

#include <cstdio>

void foo( int i, char const* c_str_1, char const* c_str_2 )
{
   printf( "foo( int i, char const* c_str_1, char const* c_str_2 )\n" );
}

template< std::size_t N, std::size_t M >
void foo( int i, char const (&c_str_1)[N], char const (&c_str_2)[M] )
{
   printf( "foo( int i, char const (&c_str_1)[N], char const (&c_str_2)[M] )\n" );
}


int main( int argc, char* argv[] )
{
   char const* c_strg_1 = "This is a c style string.";
   foo( 1, c_strg_1, "bla" );
   foo( 1, "bla", "bla" );
   return 0;
}

这可能是我明显遗漏的东西,但编译器总是选择char const* 重载。我原以为模板是完全匹配的,而另一个需要“衰减”/“转换”。

无论如何,感谢任何对此有洞察力的人。

【问题讨论】:

  • 值得注意的是,在这两个调用中,唯一可能与您的模板匹配的是第二个。第一个显然不是,也永远不可能。
  • 你也可以是明确的:foo&lt;&gt;(1, "bla", "bla");
  • @Barry 发布后,我继续调查这个问题,我还找到了这个答案 (stackoverflow.com/questions/43732122/…),它可能被认为是重复的。我想我应该点击“这解决了我的问题”按钮来接受副本并关闭问题,但按钮没有出现。对不起

标签: c++ c++11 templates overload-resolution


【解决方案1】:

在重载决议期间,通常的函数总是优先于函数模板。

这意味着,如果有可能接受适当参数的foo 重载(即使函数模板看起来更匹配),那么编译器将选择这个重载。

除此之外,对于第一次通话:

foo( 1, c_strg_1, "bla" );

由于c_strg_1 的类型为const char*,因此无法实例化函数模板。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2012-05-25
    相关资源
    最近更新 更多