首页 > 解决方案 > 当给定 const char * 作为模板化参数的类型时,为什么编译器会选择 bool 而不是 string_view?

问题描述

#include <iostream>

struct A
{
    void update(bool const & v)
    {
        std::cout << std::boolalpha << v << std::endl;
    }

    void update(std::string_view v)
    {
        std::cout << v << std::endl;
    }
};


template <typename T>
void update(T const & item)
{
    A a;
    a.update(item);
}


int main()
{
    const char * i = "string";
    update(i);
}

当我用 a 调用 update 时const char *,编译器用bool参数而不是string_view?! 为什么 ??!

标签: c++c++17template-meta-programmingoverload-resolution

解决方案


const char *to的转换std::string_view(通过 的构造函数std::string_view)是用户定义的转换;这比重载决议中的标准转换(从to的隐式转换)更差。const char*bool

1) 标准转换序列总是优于用户定义的转换序列或省略号转换序列。


推荐阅读