考虑以下课程
template <typename T>
struct A
{
T x;
};
Run Code Online (Sandbox Code Playgroud)
现在,另一个类是这样的模板:
template <typename T, typename U>
class B
{
protected:
std::vector<U> arr;
public:
T get_x(unsigned int p) { return arr[p].x; }
};
Run Code Online (Sandbox Code Playgroud)
我想A<T>::x从内部访问该字段B<T, A<T>>::get_x()并将其保持不变(即保持其类型T).我对模板的不了解说,这需要知道T它的类型和它应该是模板参数之一class B.然而,这使得可以声明不一致的东西,例如B<int, A<double>>,并且通常听起来像是不必要的重复.
T的A<T>::x,避免两个模板类型?感觉就像是重复,所以我不确定是否有一个敬畏上帝,标准持久的解决方案.对于它的价值,我使用GCC 4.6.2和-std = c ++ 0x.
我建议标准库采用一种方法。定义嵌套类型。
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
};
Run Code Online (Sandbox Code Playgroud)
用法:
B<A<int>> ba; //'>>' if C++11, otherwise use '> >' (separate them by space)
B<C<double>> bc; //works for C class template as well
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |