替代typedef的模板声明 [英] Alternative to template declaration of typedef

查看:330
本文介绍了替代typedef的模板声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要完成

namespace NTL
{
    typedef std::valarray vector;
}

我知道这是不允许的,但我需要一个快速和简单的方法(不重新实现所有的函数,操作符,重载等)得到一个模板typedef。

through standard C++. I know it's not allowed, but I need a quick and easy way (without reimplementing all functions, operators, overloads, etc.) to get a template typedef.

现在做一个模板类Vector有一个valarray作为数据成员,但这将要求我重载所有的数学函数为我的矢量(再次...作为valarray也一样)。

I am now doing a template class Vector which has a valarray as data member, but that will require me to overload all math functions for my vector (again... as valarray does it as well).

任何想法?谢谢!

PS:我可能需要扩展 NTL :: vector 的功能,

PS: I will probably need to extend the functionality of NTL::vector at some point, and a way to incorporate that in the solution would be awesome.

推荐答案

在C ++ 0x中,这将是非常简单,但对于现在你可以通过两种方式来处理这个问题,通过元函数或者滥用继承。

In C++0x that will be really simple, but for the time being you can approach the problem in two ways, through a metafunction or by abusing inheritance.

namespace NTL {
   // metafunction
   template <typename T>
   struct vector_1 {
      typedef std::valarray<T> type;
   };

   // inheritance abuse:
   template <typename T>
   struct vector_2 : std::valarray<T>
   {};
}
int main() {
   NTL::vector_1<double>::type var1; // type is std::valarray<double>
   NTL::vector_2<double> var2;       // type inherits from std::valarray<double>
}

第二种方法可以轻松扩展,但请注意,推荐从STL容器公开继承,因为它们不是为了扩展而设计的。特别是因为它们没有虚拟析构函数,如果你的对象从指向STL容器的指针 delete d,你可能会遇到未定义的行为...

The second approach can be extended easily, but note that in general it is not recommended to inherit publicly from STL containers, as they were not designed to be extended. In particular since they don't have virtual destructor you can end up with undefined behavior if your object is deleted from a pointer to the STL container...

我建议你通过使用声明来私下继承基础成员函数,遗产)。它将需要更多的样板代码,但是你不需要为所有你想要的接口提供转发方法。

I would advise you to inherit privately and bring the base member functions into scope by means of a using declaration (better than providing public inheritance). It will require more boiler-plate code, but you won't need to provide forwarding methods for all your desired interface.

BTW,C ++ 0x方式:

BTW, the C++0x way would be:

namespace NTL {
   template <typename T>
   using vector = std::valarray<T>;
}

这篇关于替代typedef的模板声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆