考虑代码:
#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)};
}
现在我可以,例如使用from_string
函数,如下所示:
string s = "123";
int x = from_string(s);
cout << x << endl;
我很好奇是否有办法调用converter
struct的强制转换操作符显式指定模板参数。语法:
from_string(s).operator int<int, converter_impl<int>>();
不起作用......
答案 0 :(得分:1)
您可以调用强制转换操作符,因为它不是模板化的:
int x = from_string(s).operator int();
或者像这样
int x = from_string(s).template operator int();
作为明确指定第二个模板参数的解决方法:
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;
}
};
并像这样使用它:
auto y = from_string(s).cast<int, converter_impl<int> >();