您拥有的代码在验证方面没有任何作用。相反,它会根据传递的常量生成一个 UUID(如哈希函数)。
仔细一看,我错了。缺少的验证似乎是对版本的检查:
Live On Coliru
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/string_generator.hpp>
#include <iostream>
bool is_valid_uuid(std::string const& maybe_uuid, boost::uuids::uuid& result) {
using namespace boost::uuids;
try {
result = string_generator()(maybe_uuid);
return result.version() != uuid::version_unknown;
} catch(...) {
return false;
}
}
int main() {
std::string maybe_uuid;
std::cout << "Enter a UUID: ";
while (std::cin >> maybe_uuid)
{
boost::uuids::uuid result;
bool is_valid = is_valid_uuid(maybe_uuid, result);
std::cout << "\n'" << maybe_uuid << "' valid: " << std::boolalpha << is_valid << "\n";
if (is_valid)
std::cout << "Parsed value: " << result << "\n";
}
}
Coliruecho 00000000-0000-{0,4}000-0000-000000000000 $(uuidgen) "{$(uuidgen)}" | ./a.out
的示例输出:
Enter a UUID:
'00000000-0000-0000-0000-000000000000' valid: false
'00000000-0000-4000-0000-000000000000' valid: true
Parsed value: 00000000-0000-4000-0000-000000000000
'a2c59f5c-6c9b-4800-afb8-282fc5e743cc' valid: true
Parsed value: a2c59f5c-6c9b-4800-afb8-282fc5e743cc
'{82a31d37-6fe4-4b80-b608-c63ec5ecd578}' valid: true
Parsed value: 82a31d37-6fe4-4b80-b608-c63ec5ecd578