Search code examples
c++templatestemplate-specializationpartial-specialization

string to type function, template specialization to make call uniform


Is there a unique way to achieve a uniform call syntax for a convert function like the following for any kind of type? The function takes a string and converts it into the given TYPE (here int and MyMatrix<double>::Vector3 , call by reference of course!!)

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);

e.g:

template<typename T>
struct MyMatrix{
    typedef Eigen::Matrix<T,3,1> Vector3;
};

I would like that the convert function converts types in the form of Eigen::Matrix<T,3,1> with T arbitary with the same function,

It should also support the basic types which have no template parameters (like the int)


Solution

  • You may want something like that:

    #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;
    }