Skip to content

Instantly share code, notes, and snippets.

@shininglion
Last active August 9, 2018 14:52
Show Gist options
  • Save shininglion/6e4d1149f43439c3836674a94a1a3441 to your computer and use it in GitHub Desktop.
Save shininglion/6e4d1149f43439c3836674a94a1a3441 to your computer and use it in GitHub Desktop.
compile-time if can have code not able to be compiled with regular if
// Example from: C++17-The Complete Guide, by Nicolai M. Josuttis
// Chapter 10. Compile-Time if
// http://www.cppstd17.com/
#include <string>
#include <iostream>
template <typename T>
std::string toString_constexpr_if(T x)
{
if constexpr(std::is_same_v<T, std::string>) {
return x; // statement invalid, if no conversion to string
}
else if constexpr(std::is_arithmetic_v<T>) {
return std::to_string(x); // statement invalid, if x is not numeric
}
else {
return std::string(x); // statement invalid, if no conversion to string
}
}
template <typename T>
std::string toString_regular_if(T x)
{
if (std::is_same_v<T, std::string>) {
return x; // statement invalid, if x is numeric
}
else if (std::is_arithmetic_v<T>) {
return std::to_string(x); // statement invalid, if x is std::string
}
else {
return std::string(x); // statement invalid, if x is numeric
}
}
int main()
{
std::cout << toString_constexpr_if(42) << '\n';
std::cout << toString_constexpr_if(std::string("hello")) << '\n';
std::cout << toString_constexpr_if("hello") << '\n';
// The following statements will have compilation error
//std::cout << toString_regular_if(42) << '\n';
//std::cout << toString_regular_if(std::string("hello")) << '\n';
//std::cout << toString_regular_if("hello") << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment