gpt4 book ai didi

c++ - 一致的模板类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:36:25 25 4
gpt4 key购买 nike

问题

考虑下面的类

template <typename T>
struct A
{
T x;
};

现在,另一个类是这样模板化的:

template <typename T, typename U>
class B
{
protected:
std::vector<U> arr;

public:
T get_x(unsigned int p) { return arr[p].x; }
};

我想访问字段 A<T>::x来自内部 B<T, A<T>>::get_x()并原样返回(即,保持其类型为 T )。我对模板的了解很少,这需要知道类型 andof T它应该是 class B 的模板参数之一.然而,这使得声明不一致的东西成为可能,比如 B<int, A<double>> ,并且通常听起来像是不必要的重复。

问题

  1. 我写的是不良编程习惯的例子吗?应该怎么写?
  2. 是否有可能推断类型 TA<T>::x并避免两种模板类型?这感觉像是重复,所以我不确定是否有敬畏上帝、遵守标准的解决方案。

就其值(value)而言,我使用的是带有 -std=c++0x 的 GCC 4.6.2。

最佳答案

我会建议标准库采用的方法。定义嵌套类型。

template <typename T>
struct A
{
typedef T value_type; //this is nested type to be used by B
T x;
};

//this is another class added by me, just to demonstrate the genericity
template <typename T>
struct C
{
typedef T value_type; //this is nested type to be used by B
T x;
};

template <typename T>
class B
{
typedef typename T::value_type value_type; //get the nested type
protected:
std::vector<T> arr;

public:
value_type get_x(unsigned int p) { return arr[p].x; }
//^^^^^^^^^ note this
};

用法:

 B<A<int>> ba;    //'>>' if C++11, otherwise use '> >' (separate them by space)
B<C<double>> bc; //works for C class template as well

关于c++ - 一致的模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8192358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com