I want to match for certain data types using a templated C++
function and if none of the constexpr
cases are matched, I want to cause a compilation error:
template<typename ValueType>
void match_data_type() {
if constexpr (std::is_same_v<ValueType, bool>) {
std::cout << "bool" << std::endl;
} else if constexpr (std::is_same_v<ValueType, const char *>) {
std::cout << "const char *" << std::endl;
} else if constexpr (std::is_same_v<ValueType, std::string>) {
std::cout << "std::string" << std::endl;
} else {
std::cout << "Not matched!" << std::endl;
// static_assert(false, "Unhandled data type");
}
}
Example usage:
match_data_type<bool>();
match_data_type<char *>();
match_data_type<std::string>();
match_data_type<std::stringstream>();
Output:
bool
const char *
std::string
Not matched!
Is it possible that unmatched data type cases cause a compilation error and if yes, how can it be implemented? static_assert
does not work since it always takes effect, no matter where it is placed in the code (e.g. uncommenting the line above will always cause an assertion error regardless of the context). Note that I do not want to throw an exception but rather prevent the unhandled data type to be passed to match_data_type()
at all.