是否有一种独特的方法可以为任何类型的转换函数实现统一的调用语法,如下所示?该函数接受一个字符串并将其转换为给定的 TYPE(此处为 int
和 MyMatrix<double>::Vector3
,当然是通过引用调用!!)
int a;
std::string b = "asd";
stringToType::call(a,b);
MyMatrix<double>::Vector3 g; // Vector3 might be any type e.g Eigen::Matrix<double,3,1>
stringToType::call(g,b);
例如:
template<typename T>
struct MyMatrix{
typedef Eigen::Matrix<T,3,1> Vector3;
};
我希望转换函数以 Eigen::Matrix<T,3,1>
的形式转换类型与 T
具有相同功能的任意,
它还应该支持没有模板参数的基本类型(比如 int
)
最佳答案
你可能想要这样的东西:
#include <string>
#include <sstream>
namespace details
{
template <typename T>
struct stringToTypeImpl
{
void operator () (std::stringstream& ss, T& t) const
{
ss >> t;
}
};
// And some specializations
template <typename T, int W, int H>
struct stringToTypeImpl<Eigen::Matrix<T, W, H> >
{
void operator () (std::stringstream& ss, Eigen::Matrix<T, W, H>& t) const
{
for (int j = 0; j != H; ++j) {
for (int i = 0; i != W; ++i) {
stringToTypeImpl<T>()(ss, t(i, j)); //ss >> t(i, j);
}
}
}
}
// ...
}
template <typename T>
void stringToType(const std::string& s, T& t)
{
std::stringstream ss(s);
details::stringToTypeImpl<T>()(ss, t);
}
int main() {
std::string s = "42";
int i;
stringToType(s, i);
return 0;
}
关于c++ - 字符串类型函数,模板特化使调用统一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18789349/