mirror of
https://github.com/CLIUtils/CLI11.git
synced 2025-04-28 19:53:52 +00:00
String conversions (#421)
* add a variant of the string conversions for the default string operations. Discriminate between the is_convertible and is_constructible type traits for object. * update the test to test the different situations with the funny string like type
This commit is contained in:
parent
6b7f6a7480
commit
ee851c7e88
@ -219,15 +219,24 @@ template <typename S> class is_tuple_like {
|
||||
};
|
||||
|
||||
/// Convert an object to a string (directly forward if this can become a string)
|
||||
template <typename T, enable_if_t<std::is_constructible<std::string, T>::value, detail::enabler> = detail::dummy>
|
||||
template <typename T, enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
|
||||
auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
|
||||
return std::forward<T>(value);
|
||||
}
|
||||
|
||||
/// Construct a string from the object
|
||||
template <typename T,
|
||||
enable_if_t<std::is_constructible<std::string, T>::value && !std::is_convertible<T, std::string>::value,
|
||||
detail::enabler> = detail::dummy>
|
||||
std::string to_string(const T &value) {
|
||||
return std::string(value);
|
||||
}
|
||||
|
||||
/// Convert an object to a string (streaming must be supported for that type)
|
||||
template <typename T,
|
||||
enable_if_t<!std::is_constructible<std::string, T>::value && is_ostreamable<T>::value, detail::enabler> =
|
||||
detail::dummy>
|
||||
enable_if_t<!std::is_convertible<std::string, T>::value && !std::is_constructible<std::string, T>::value &&
|
||||
is_ostreamable<T>::value,
|
||||
detail::enabler> = detail::dummy>
|
||||
std::string to_string(T &&value) {
|
||||
std::stringstream stream;
|
||||
stream << value;
|
||||
|
@ -1885,6 +1885,27 @@ TEST_F(TApp, VectorUnlimString) {
|
||||
EXPECT_EQ(answer, strvec);
|
||||
}
|
||||
|
||||
// From https://github.com/CLIUtils/CLI11/issues/420
|
||||
TEST_F(TApp, stringLikeTests) {
|
||||
struct nType {
|
||||
explicit nType(const std::string &a_value) : m_value{a_value} {}
|
||||
|
||||
explicit operator std::string() const { return std::string{"op str"}; }
|
||||
|
||||
std::string m_value;
|
||||
};
|
||||
|
||||
nType m_type{"abc"};
|
||||
app.add_option("--type", m_type, "type")->capture_default_str();
|
||||
run();
|
||||
|
||||
EXPECT_EQ(app["--type"]->as<std::string>(), "op str");
|
||||
args = {"--type", "bca"};
|
||||
run();
|
||||
EXPECT_EQ(std::string(m_type), "op str");
|
||||
EXPECT_EQ(m_type.m_value, "bca");
|
||||
}
|
||||
|
||||
TEST_F(TApp, VectorExpectedRange) {
|
||||
std::vector<std::string> strvec;
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user