用字符串而不是类型进行模板化

F. *_*ivé 1 c++ templates boost-variant

我想创建一个适用于多种类型的类.然而,我想要实例化这个类的元素,而不是使用类型,而是使用字符串(例如,使用"int"而不是int),这样我就不必在使用这个类时使用大量的调度程序函数.

在一个小班上Tab,我尝试了两个"解决方案":

第一个:

template <typename T>
class Tab {
public :

  Tab(std::size_t length) {
    T* tab_[length];
    tab = tab_;
  }

  T* tab;

  T operator[](std::size_t i) {
    return tab[i];
  }
}; 

Tab getTab(std::string type, std::size_t length) {

    if (type == "int") {
      Tab<int> tab(length);
    } else if (type == "double") {
      Tab<double> tab(length);
    }

    return tab;
}
Run Code Online (Sandbox Code Playgroud)

第二个:

typedef boost::variant<int, double> numeric;
typedef boost::variant<int*, double*> numeric_ptr;

class Tab {
public :

  Tab(std::string type, std::size_t length) {
    if (type == "int") {
      tab = new int[length];
    } else if (type == "double") {
      tab = new double[length];
    }
  }

  numeric_ptr tab;

  numeric operator[](std::size_t i) {
    return tab[i];
  }
}; 
Run Code Online (Sandbox Code Playgroud)

两次尝试都不编译.我很乐意为我的问题找到一个不那么复杂的解决方案.

编辑:为什么你首先使用字符串而不是类型名?

我有很多使用模板化类的函数.在每个函数中,我可以将模板化类的类型名称作为字符串知道,因此我必须使用类似这样的调度函数:https://github.com/privefl/bigstatsr/blob/master/src/colstats.cpp.如果你有20个这样的函数,那么为它们中的每一个编写一个调度函数真的很烦人(并且它很容易出错).

所以我宁愿只为一个类的实例化创建一个调度函数,并在需要这个模板化类的一个实例的所有函数中使用这个函数.

Jar*_*d42 5

你可以这样做:

template <typename T>
class Tab {
public:
  Tab(std::size_t length) : tab(length) {}

  // ...
private:
    std::vector<T> tab;
}; 

boost::variant<Tab<int>, Tab<double> >
CreateTab(const std::string& type, std::size_t length)
{
    if (type == "int") {
        return Tab<int>(length);
    } else if (type == "double") {
        return Tab<double>(length);
    }
    throw std::runtime_error("Bad type");
}
Run Code Online (Sandbox Code Playgroud)