如何从其他类型获取类型(C++ 模板元编程)

How to get a type from other type (C++ template metaprogramming)

我对 C++ 模板元编程还很陌生,并尝试做以下事情。假设我有一个像这样的自定义模板 class

template<typename Parameter>
class MYCLASS {
public:
    Parameter parameter;
    //Do something with it
};

现在为了让用户实例化class,he/she需要做

#include "other.h" //A header from other libraries
MYCLASS<other::someclass> myclass; //Suppose there is a class called  other::someclass in the "other.h"

我想让用户免于寻找 header 的问题,我想尝试使用元编程,像这样

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_ 应该 return 另一种类型。例如,它应该采用双参数和 return 和 other::someclass,因此 class 定义应该类似于

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 是某个变量还是某个类型别名!您需要向编译器指定 "Hey, I am saying 'type' is a typename, so use it that way"。因此使用 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;