I'm still new to the C 20 concepts and I want to know why this does not work. I want to create a function template that concatenates numbers as strings. So I wanted to try concepts. I used std::convertible_to
to check whether the entered datatype (which is int
in this case) can be converted to std::string
. But I'm facing an error that I don't understand.
//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;
}
Error:
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);
What am I doing wrong ?
CodePudding user response:
You appear to want a concept for types that can be passed to std::to_string()
.
This code will achieve that.
template <typename T>
concept ConvertibleToStdString = requires(T a){ std::to_string(a); };
What am I doing wrong ?
You are misunderstanding the meaning of std::convertible_to<T,std::string>
.
That concept validates (among other things) that T
can implicitly convert to a std::string
, as in:
std::string s;
s = 623; // This will NOT compile. int is not convertible_to std::string