作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 C++ 模板元编程还很陌生,并尝试做以下事情。假设我有一个像这样的自定义模板类
template<typename Parameter>
class MYCLASS {
public:
Parameter parameter;
//Do something with it
};
现在为了让用户实例化类,他/她需要做
#include "other.h" //A header from other libraries
MYCLASS<other::someclass> myclass; //Suppose there is a class called other::someclass in the "other.h"
我想让用户省去查找标题的问题,我想尝试使用元编程,像这样
template<typename Type>
struct get_right_type_impl{
//Do something here
};
template<typename Type>
using get_right_type_ = get_right_type_impl<Type>::type;
其中 get_right_type_ 应该返回另一种类型。例如,它应该接受一个双参数并返回一个 other::someclass,因此类定义应该如下所示
template<typename Type>
class MYCLASS {
public:
get_right_type_<Type> parameter;
//when Type==double, get_right_type_<Type> should be equivalent to other::someclass
};
//Now one can use instantiation like this
MYCLASS<double> class;
我已经尝试了一些东西,主要是遵循this .虽然我想我得到了一些文章,但我没有编造通常在类型名称的使用方面存在编译问题的示例。从这个论坛上阅读了一些答案后,我变得更加困惑,并且不确定这在我们的案例中是否可行,因为我也没有从谷歌搜索中找到确切的解决方案。
欢迎任何建议。
最佳答案
template<typename Type>
using get_right_type_ = get_right_type_impl<Type>::type;
考虑一下编译器看到它时的想法。它不知道 ::type
是某个变量还是某个类型别名!您需要向编译器指定“嘿,我是说‘type’是一个类型名,所以这样使用它”。因此使用 typename
关键字来明确说明后面是一个类型。
继续,get_right_type
基本上需要是一个类型到类型的映射。做到这一点相当容易。
template <typename T> struct get_right_type;
template <> struct get_right_type<double> { using type = class_for_double; }
template <> struct get_right_type<int> { using type = class_for_int; }
考虑上面的类型映射在一些 header 中说'common_mapping.h'。您可以执行以下操作:
#include "common_mapping.h"
get_right_type<int>::type a;
关于c++ - 如何从其他类型获取类型(C++ 模板元编程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420352/
我是一名优秀的程序员,十分优秀!