For example, I've got this:
// Code A
int create_int() { return 42; }
double create_double() { return 3.14; }
std::string create_string() { return {"Hi"}; }
Now let's assume that it makes sense to put these creates together, so I rewrite the code:
// Code B
template <typename T> T create();
template <> int create<int>() { return 42; }
template <> double create<double>() { return 3.14; }
template <> std::string create<std::string>() { return {"Hi"}; }
Or even:
// Code C
#include <type_traits>
template <typename T> T create()
{
if constexpr (std::is_same_v<T, int>)
{
return 42;
}
else if constexpr (std::is_same_v<T, double>)
{
return 3.14;
}
else if constexpr (std::is_same_v<T, std::string>)
{
return {"Hi"};
}
else
{
// static_assert(false);
return static_cast<T>(0);
}
}
I wanna to know is there any difference between these codes, or is it just about code style.