带有const模板参数的模板模板类

时间:2011-05-13 22:56:41

标签: c++ templates const

我不明白为什么不编译:

struct  A
{};  

template<class T> 
struct  B
{};  

template<template<class> class T1, class T2> 
struct C
{};

int
main  (int ac, char **av)
{
  typedef B<double> b;              //compiles
  typedef B<const double> b_const;  //compiles
  typedef B<A> ba;                  //compiles
  typedef B<const A> ba_const;      //compiles

  typedef C<B,double> c1;           //compiles
  typedef C<B,const double> c2;     //compiles
  typedef C<const B,double> c3;     //ISO C++ forbids declaration of ‘type name’ with no type
}

(我发现对标准的引用有点神秘)

我需要更改哪些内容才能编译?

修改

编译器详细信息(似乎相关):

Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.4.4-14ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.4 --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5) 

EDIT2:

通过解释,我试图做这样的事情:

template<template<class> class TheContainer, class T> 
struct Iterator

template<class T> 
struct  Container

typedef Iterator<Container, double> iterator;
typedef Iterator<const Container, double> const_iterator;

非模板化容器的技术可在此提升文档末尾找到:http://www.boost.org/doc/libs/1_46_1/libs/iterator/doc/iterator_facade.html

我想解决方案不是嵌套模板。回想起来,这似乎很明显。

4 个答案:

答案 0 :(得分:4)

C的第一个参数不是一个类型,因此将const-type作为其arg传入是没有意义的。模板不能是const或非const,只有类型可以是const或非const。 const B甚至意味着什么?

const int有道理。 const vector<int>vector<const int>一样有道理。但是const vector意味着什么?

(捏盐警告:在看到这个问题之前,我甚至都不知道模板模板类。)

为了使这更具体,想象B和C是:

template<class T>
struct  B
{
        T t;
};      

template<template<class> class T1, class T2>
struct C
{
        T2 t2;
        T1<T2> t1;
};

c2的类型为

C<B,const double>   
==>   struct { const double t2; T1<const double> t1;}
==> struct { const double t2; struct { const double b; } t1;}

你期望c3是什么?那个t1本身就是const,而t1.b是非const的?我认为这是有道理的。

答案 1 :(得分:2)

这个确切的代码在VS2010中编译。我不知道你编译器,但我建议你检查编译器开发人员的bug数据库,如果这样的bug没有注册。

我会在GCC中试一试。


Ok GCC(4.5.1)确实给出了错误。我想我们必须等待具有标准知识的人知道它是标准行为还是错误。


CLang(2.8)确实给出了相同的错误(完全相同的消息)。

答案 2 :(得分:1)

我猜B不能是const因为此时它没有真正的类型而且编译器不知道什么是const。除了离开const之外,我无法提出正确编译的解决方案,因为模板模板对大脑来说真是一种痛苦。

答案 3 :(得分:1)

我敢打赌,MSVC以与const classes相同的方式默默地吞噬const

相关问题