一般具有一次重载函数和可选的自动转换

问题描述 投票:0回答:1

根据以下代码的标准,未调用带有字符指针的字符串构造函数的原因是什么?

#include <iostream>

using namespace std;

void fn( string const &str )
{
    cout << str;
}

template<typename T>
void fn( T param )
{
    cout << param << endl;
}

int main()
{
    fn( string( "hello world" ) );
    fn( "hello world" );
}
c++
1个回答
0
投票

根据以下代码的标准,未调用带有字符指针的字符串构造函数的原因是什么?

对于第二次调用

fn("hello world");
,函数模板的参数
param
不需要转换为
std::string
,而非函数模板需要转换为
std::string

也就是说,对于调用来说,函数模板比非函数模板更好匹配

fn("hello world");

© www.soinside.com 2019 - 2024. All rights reserved.