Can someone explain me what is wrong with my function and how to fix it ?
If the input are integers it should return them as a string
If they are doubles -> set_precision(4) then return them as a string
Also is there a posibility to apply set_precision() to multiple var. in one line ?
Thanks for your replies
#include <iostream>
#include<iomanip>
#include<string>
#include<type_traits>
template<typename T>
std::string nums_to_string(T a, T b){
if (std::is_integral<T>){
return (std::to_string(a) std::to_string(b));
}
std::cout << std::setprecision(4) << std::fixed << a;
std::cout << std::setprecision(4) << std::fixed << b;
return (std::to_string(a) std::to_string(b));
}
int main()
{
double x{ 22.55 };
double y{ 50.65 };
//std::cout << std::setprecision(4) << std::fixed << x;
/*std::string sX = std::to_string(x);
std::cout << sX;*/
std::cout << nums_to_string(x, y);
}`
CodePudding user response:
The documentation says that to check that the type is an intregal, you need to check the 'value' attribute within is_integral. Here the code:
template<typename T>
std::string nums_to_string(T a, T b){
if (std::is_integral<T>::value){
return (std::to_string(a) std::to_string(b));
}
std::cout << std::setprecision(4) << std::fixed << a;
std::cout << std::setprecision(4) << std::fixed << b;
return (std::to_string(a) std::to_string(b));
}
As mentioned by someone else, since version 17, is_integral<T>::value
has been replaced by is_integral_v<T>
CodePudding user response:
Thank you all , now I got this right. The main problem was with unnecessary std::cout
and with wrong form of std::is_integral_v<>