字符串到类型函数,模板专用化使调用统一

string to type function, template specialization to make call uniform

本文关键字:调用 专用 类型 函数 字符串      更新时间:2023-10-16

有没有一种独特的方法来实现转换函数的统一调用语法,如下所示?该函数获取一个字符串并将其转换为给定的 TYPE(此处为 intMyMatrix<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;
}