C++ 基于模板类型的类的类型

C++ 基于模板类型的类的类型,c++,C++,考虑以下情况: #include<iostream> template<class U> class Table_Inside { U a; }; template<class T> class Table { Table_Inside<T> *tmp; }; int main() { Table<int> obj; } 所以,如果我通过 Table<int> obj Table<char>

考虑以下情况:

#include<iostream>

template<class U>
class Table_Inside {
  U a;
};

template<class T>
class Table {
  Table_Inside<T> *tmp;
};

int main() {
  Table<int> obj;
}
所以,如果我通过

Table<int> obj
Table<char> obj
它应该创建
Table\u Inside\u char
Inside
Table
class类型的指针(tmp)


在C++世界中是否有可能?

这可以通过专业化来完成:

//基本的一般情况
模板
类表_内;
模板
类表_内
{
//字符的特殊实现
};
模板
类表_内
{
//整数的特殊实现
};
模板
类表
{
表_内*tmp;
};

如果您需要在
char
int
类之间共享公共功能,那么您可以使用继承来实现这一点。

您可以通过一些特性来处理这一点。定义

// Primary template
template <class T>
struct Table_Trait;

// Specialization
template <>
struct Table_Trait<int> { using type = Table_Inside_int; };

template <>
struct Table_Trait<char> { using type = Table_Inside_char; };

template <class T>
using Table_Inside_t = typename Table_Trait<T>::type;

如果专门化不起作用,并且只有两种类型,则可以使用和生成别名:

//假定只传递char或int
模板
使用表\u Inside=std::conditional\u t;

这可以像以前一样使用,如
表\u in

是。这很容易做到。我不知道我生活在哪个世界谢谢,你还想要什么
Table_Inside
Table_Inside_char
Table_Inside_int
的类型别名,具体取决于
T
是什么<代码>条件和
是相同的
是标准提供的类型特征library@kmdredo,我应该在哪里写这份声明?“表”类的外部/内部?我显然不知道这个的用法部分。它可以是内部的,也可以是外部的,但它只在内部定义了类型
Table\u
,而
tmp
声明必须是单独的。这是一个显示它工作的例子。或者我假设您可以像现在这样直接声明类型,而不是别名,该示例既有c++14(如上所述)又有c++11变体。
// The "base" generic case
template<typename T>
class Table_Inside;

template<>
class Table_Inside<char>
{
    // Special implementation for characters
};

template<>
class Table_Inside<int>
{
    // Special implementation for integers
};

template<typename T>
class Table
{
    Table_Inside<T>* tmp;
};
// Primary template
template <class T>
struct Table_Trait;

// Specialization
template <>
struct Table_Trait<int> { using type = Table_Inside_int; };

template <>
struct Table_Trait<char> { using type = Table_Inside_char; };

template <class T>
using Table_Inside_t = typename Table_Trait<T>::type;
template<class T>
class Table {
    Table_Inside_t *tmp;
};
// Primary template
template <class T>
class Table_Inside;

// Specialization
template <>
class Table_Inside<int> { /* implementation for int */ };

template <>
class Table_Inside<char> { /* implementation for char */ };
// assumes only char or int will be passed
template <class T>
using Table_Inside = std::conditional_t<std::is_same_v<T, char>, Table_Inside_char, Table_Inside_int>;