Consider the code:
#include <string>
#include <sstream>
template <class T>
struct converter_impl {
std::string to_convert;
operator T() {
T result;
std::stringstream ss(to_convert);
ss >> result;
return result;
}
};
struct converter {
std::string to_convert;
template <class T, class CI = converter_impl<T>>
operator T() {
CI ci = CI{std::move(to_convert)};
return ci;
}
};
converter from_string(std::string s) {
return converter{std::move(s)};
}
Now I can e.g. use the from_string
function as follows:
string s = "123";
int x = from_string(s);
cout << x << endl;
I am just curious if there is a way to call the cast operator of converter
struct explicitly specifying the template parameters. The syntax:
from_string(s).operator int<int, converter_impl<int>>();
does not work...
You can call cast operator either as it is not templated:
int x = from_string(s).operator int();
or like this
int x = from_string(s).template operator int();
As workaround to specify second template parameter explicitly:
struct converter {
std::string to_convert;
template <class T, class CI >
operator T() {
CI ci = CI{std::move(to_convert)};
return ci;
}
template <class T, class CI>
T cast()
{
CI ci = CI{std::move(to_convert)};
return ci;
}
};
and use it like this:
auto y = from_string(s).cast<int, converter_impl<int> >();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With