【问题标题】:Cannot call constructor (template-template parameter)无法调用构造函数(模板模板参数)
【发布时间】:2017-06-26 17:18:42
【问题描述】:

不知何故,我无法创建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) {}
    ^

【问题讨论】:

  • 发生这种情况有什么原因吗?
  • 可能是non-deduced context
  • 最后一个错误说C&lt;A&gt; &amp;,所以我猜A没有推导出来。
  • 我认为A 很好;请参阅here,在那里我得到了一些代码来编译和运行A。我的示例和您的示例之间的区别在于 C 是在具体类(而不是另一个模板类)上模板化的。也许这就是问题所在?模板层太多导致编译器放弃?

标签: c++ c++11 templates constructor template-templates


【解决方案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);
 }

【讨论】:

  • 当我看到这段代码时,我很困惑,但我很高兴这可以工作。就是不知道为什么……
  • @rxu - 这只是模板化的另一个层次; D 的模板参数是一个模板类型,其参数不是类型而是模板模板。所以D 的模板参数是(如果我可以使用这个表达式)带有模板模板参数的模板模板模板。我的示例(专业化)展示了如何提取 D 参数的模板模板参数。这不是很清楚吗? :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-13
  • 2023-01-30
相关资源
最近更新 更多