字符串到类型函数,模板专用化使调用统一
string to type function, template specialization to make call uniform
有没有一种独特的方法来实现转换函数的统一调用语法,如下所示?该函数获取一个字符串并将其转换为给定的 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;
}
相关文章:
- 调用专用模板时出错"no matching function for call to [...]"
- 将"模板<类型名 T>zero()"扩展/专用为可调用的"T"
- 基于枚举参数调用专用模板方法
- 调用模板专用化,具有更多参数的单参数模板调用的特定值
- 从非模板类调用专用模板方法
- 通过引用调用模板专用化
- 从部分专用模板方法调用模板非静态方法
- 是否可以在没有显式专用化的情况下调用可变参数模板函数?
- 调用专用 std::move()
- 可变参数模板必须具有可调用的专用化,非空参数包才能正确格式化
- 从专用模板方法调用无专门化的模板方法
- 未调用数组的函数专用化
- 模板类专用化函数调用.C++
- 对于重载函数,为父实例和子实例调用专用版本
- 为什么在第二次调用时使用默认参数时此模板专用化失败
- 不会调用模板化构造函数的专用模板
- C++调用模板专用函数
- 关于调用具有专用模板的类的混淆
- 字符串到类型函数,模板专用化使调用统一
- 调用专用模板函数时强制编译时错误