理解c++20中的convertible_to概念

Gas*_*ton 4 c++ c++-concepts c++20

我对 C++20 概念仍然很陌生,我想知道为什么这不起作用。我想创建一个将数字连接为字符串的函数模板。所以我想尝试一些概念。我曾经std::convertible_to检查输入的数据类型(int在本例中)是否可以转换为std::string. 但我面临着一个我不明白的错误。

//building the concept
template <typename T>
concept ConvertibleToStdString = std::convertible_to<T,std::string>;

//using the concept
template <ConvertibleToStdString T>
std::string concatenate(T a, T b){
    return std::to_string(a) + std::to_string(b);
}

int main(){

    int x{623};
    int y{73};

    auto result = concatenate(x,y);
    std::cout << result << std::endl;
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

main.cpp:21:34: error: use of function 'std::string concatenate(T, T) [with T = int; std::string = std::basic_string<char>]' with unsatisfied constraints
   21 |     auto result = concatenate(x,y);
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

Dre*_*ann 10

您似乎想要一个可以传递给的类型的概念std::to_string()

这段代码将实现这一点。

template <typename T>
concept ConvertibleToStdString = requires(T a){ std::to_string(a); };
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

您误解了 的含义std::convertible_to<T,std::string>

该概念验证了(除其他外)T可以隐式转换为 a 的概念std::string,如下所示:

std::string s;
s = 623;   // This will NOT compile.  int is not convertible_to std::string
Run Code Online (Sandbox Code Playgroud)

  • @Gaston 该语法只是问,“`std::convertible_to&lt;T, std::string&gt;`”_compile_ 吗?它不检查评估的含义或结果。 (2认同)