无法调用构造函数(模板-模板参数)

3

我无法创建D的实例,原因不明。模板模板参数(Allocator_class)似乎是问题所在。

#include <vector>

template <template<typename T> class Allocator_class>
class T_b {
public:
    template<typename T> using A = Allocator_class<T>;
};

template< template <typename T> class A>
class C {
public:
    C() { }
};

template<typename Ttb>
class D {
public:
    template<typename T> using A = typename Ttb::template A<T>;
    typedef C<A> Data;

    D(C<A> &data) : _data(data) {}
private:
    Data &_data;
};

int main() {
    typedef T_b<std::allocator> Ttb;    
    C<std::allocator> b;
    D<Ttb>c(b);
}

来自Clang的错误:

test5.cpp:29:8: error: no matching constructor for initialization of 'D<Ttb>'
      (aka 'D<T_b<std::allocator> >')
        D<Ttb>c(b);
              ^ ~
test5.cpp:16:7: note: candidate constructor (the implicit copy constructor) not viable: no known
      conversion from 'C<std::allocator>' to 'const D<T_b<std::allocator> >' for 1st argument
class D {
      ^
test5.cpp:16:7: note: candidate constructor (the implicit move constructor) not viable: no known
      conversion from 'C<std::allocator>' to 'D<T_b<std::allocator> >' for 1st argument
class D {
      ^
test5.cpp:21:5: note: candidate constructor not viable: no known conversion from 'C<std::allocator>'
      to 'C<A> &' for 1st argument
    D(C<A> &data) : _data(data) {}
    ^

这是发生的原因吗? - hamster on wheels
也许是一个非推断上下文 - Bo Persson
最后一个错误显示 C<A> &,所以我猜测 A 没有被推导出来。 - hamster on wheels
我认为A没问题;在这里(http://ideone.com/eljdI9)我使用`A`编写了一些代码并成功运行。我的示例与你的不同之处在于,`C`是基于具体类(而不是另一个模板类)进行模板化的。也许这就是问题所在?太多层次的模板化会导致编译器放弃? - R_Kapp
CWG问题1286? - Barry
我发现如果所有东西都将类型束(T_b)作为模板参数,那么这个“东西”就可以工作。这个东西非常棘手。 - hamster on wheels
1个回答

1
我无法解释为什么你的代码会出错。
但如果你想要一个解决方案......可以使用类特化和模板模板模板参数......
#include <vector>

template <template<typename T> class Allocator_class>
class T_b
 {
   public:
      template<typename T> using A = Allocator_class<T>;
 };

template <template <typename T> class A>
class C
 {
   public:
      C() { }
 };

template <typename>
class D;

template <template <template <typename> class> class X,
          template <typename> class A>
class D<X<A>>
 {
   public:
      using Data = C<A>;

      D (Data & data) : _data(data) {}

   private:
      Data & _data;
 };

int main()
 {
    typedef T_b<std::allocator> Ttb;    

    C<std::allocator> b;

    D<Ttb> c(b);
 }

当我看这段代码时,我感到很困惑,但我很高兴它能正常运行。只是不知道为什么… - hamster on wheels
@rxu - 这只是另一种模板化的级别;D 的模板参数是一个带有非类型而是模板模板参数的模板类型。因此,D 的模板参数(如果我可以使用这个表达式)是一个带有模板模板参数的模板模板模板。我的示例(特化)展示了如何提取 D 参数的模板模板参数。这不清楚吗?:( - max66

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接