【问题标题】:inherit from template class and using inherit its constructor从模板类继承并使用继承其构造函数
【发布时间】:2018-09-29 09:44:52
【问题描述】:

我想继承一个模板类,并使用“使用”来继承它的构造函数。但是当我调用移动构造函数时,“没有匹配的构造函数”失败

#include <iostream>

template <typename ARG>
class TBase {
 public:
  TBase() {}
  TBase(TBase<ARG>&& t) {}

 private:
  ARG arg;
};

class Int : public TBase<int> {
 public:
  using TBase<int>::TBase;
};

int main() {
  TBase<int> t1;
  Int t2(std::move(t1));
  return 0;
}

构建结果

 In function 'int main()':
20:23: error: no matching function for call to 'Int::Int(std::remove_reference<TBase<int>&>::type)'
20:23: note: candidates are:
13:7: note: Int::Int()
13:7: note:   candidate expects 0 arguments, 1 provided
13:7: note: Int::Int(Int&&)
13:7: note:   no known conversion for argument 1 from 'std::remove_reference<TBase<int>&>::type {aka TBase<int>}' to 'Int&&'

【问题讨论】:

  • t1 是 TBase&lt;int&gt;,而不是 Int

标签: c++ c++11 inheriting-constructors


【解决方案1】:

嗯,这个问题很容易解释:

Default-、Copy- 和 Move- ctor 是特殊的。它们不是通过继承 ctor 继承的。详情请read more about inheriting constructors here

所以,编写你自己的接受基类实例的 ctor。应该不会太难,因为您尝试简单地继承 ctor。

【讨论】:

  • 谢谢,我知道它适用于编写自己的 ctor。我知道现在的副本和移动很特别!!!!
  • 这在 C++11 和 C++14 中是正确的,但我不确定 C++17。据我从 cppreference 和 N4659 可以看出,该代码在 C++17 中应该是有效的,但是带有 -std=c++17 的 clang++ 7.0.0 trunk 330177 仍然会以同样的错误拒绝它。
  • 啊哈 - 这在 CWG 问题 2356 中涵盖:open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2356。我认为“暂时准备就绪”的状态意味着该小组至少看过它并同意 C++17 措辞存在问题。
猜你喜欢
  • 2016-03-04
  • 2019-12-14
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2015-08-06
  • 2013-05-21
  • 1970-01-01
  • 2021-07-26
相关资源
最近更新 更多