检查编译器报错函数error(errno, ...)的入参,是否符合要求。
#include <string_view>
#include <type_traits>
// Exposition only
#define FAIL_CONSTEVAL throw
template <typename T>
struct Checker {
consteval Checker(const char* fmt) {
if (fmt != std::string_view{ "valid" }) // #1
FAIL_CONSTEVAL;
// T must be an int
if (!std::is_same_v<T, int>) // #2
FAIL_CONSTEVAL;
}
};
template <typename T>
void fmt(std::type_identity_t<Checker<T>> checked, T);
int main() {
fmt("valid", 10); // compiles
fmt("oops", 10); // fails at #1
fmt("valid", "foo"); // fails at #2
}
https://devblogs.microsoft.com/cppblog/how-we-used-cpp20-to-eliminate-an-entire-class-of-runtime-bugs/
--
FROM 61.185.187.*