c++11模板根据不同传入的字符串,来创建不同的类
时间: 2023-11-28 13:47:30 浏览: 62
这个问题可以通过模板元编程(TMP)来解决。在C++11中,我们可以使用可变参数模板和std::enable_if来实现这一功能。
首先,我们需要定义一个模板类,用于实现不同字符串对应的类的创建。我们可以使用特化来实现不同字符串对应的类的创建。例如:
```c++
template <typename T>
struct Type {};
template <>
struct Type<"int"> {
using value_type = int;
};
template <>
struct Type<"double"> {
using value_type = double;
};
// add more specializations for other types...
```
接下来,我们需要定义一个函数模板,用于根据传入的字符串来实例化对应的类。我们可以使用可变参数模板来接收传入的字符串,并使用std::enable_if来实现对应的实例化。例如:
```c++
template <typename T>
struct create_type {
static_assert(sizeof(T) == 0, "Invalid type");
};
template <typename T>
struct create_type<Type<T>> {
using value_type = typename T::value_type;
};
template <typename... Ts>
typename create_type<Type<Ts...>>::value_type create(std::string type) {
if (type == "int") {
return 0;
} else if (type == "double") {
return 0.0;
} else {
static_assert(sizeof(Ts) == 0, "Invalid type");
}
}
```
在这个函数模板中,我们首先定义了一个create_type模板类,用于根据传入的Type<T>类型来实例化对应的类。然后,在create函数模板中,我们使用std::enable_if来判断传入的字符串是否与定义的特化匹配,并调用对应的实例化函数来返回实例化的结果。
最后,在主函数中,我们可以根据不同的字符串来调用create函数模板,例如:
```c++
int main() {
auto a = create<Type<"int">>("int");
auto b = create<Type<"double">>("double");
std::cout << a << std::endl; // 0
std::cout << b << std::endl; // 0.0
return 0;
}
```
这样,我们就可以根据不同的字符串来创建不同的类了。