c++ - 字符串类型函数,模板特化使调用统一

标签 c++ templates template-specialization partial-specialization

是否有一种独特的方法可以为任何类型的转换函数实现统一的调用语法,如下所示?该函数接受一个字符串并将其转换为给定的 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;
}

关于c++ - 字符串类型函数,模板特化使调用统一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18789349/

相关文章:

c++ - libcurl 不会加载 URL 的内容

c++ - 如何将元素插入 vector 的开头?

c++ - 针对交叉模式访问的 SIMD 优化

c++,函数指针+函数模板

c++ - 在指定之前使用模板类

c++ - 使用 enable_if 专门化模板方法

c++ - 枚举类的关系运算符重载

html - 用于构建 "template builder"Web 应用程序的语言/库/模块?

c++ - 在指针类型的类模板特化中没有调用匹配函数

c++ - 模板重构