首页 > 解决方案 > 从派生类调用非模板类中的模板构造函数

问题描述

我有一个具有模板构造函数的非模板基类。在派生类中,我试图在成员初始化列表中调用基类构造函数,但它在编译器错误中失败。

#include <iostream>

template <bool>
struct helper;

template <>
struct helper<true> {
  const static bool value{true};
};

template <>
struct helper<false> {
  const static bool value{false};
};

struct timer_base {

  template <bool Bool>
  timer_base(int x) {
    std::cout << "base c'tor with value" << helper<Bool>::value << std::endl;
  }
};

struct timer : timer_base {
  timer(int x) : timer_base<false>(3) {}
};

int main() {
  timer t(4);
  return 0;

神螺栓链接: https ://godbolt.org/z/xa1Yjs

gcc给出以下错误

source>: In constructor 'timer::timer(int)':
<source>:25:18: error: 'struct timer_base timer_base::timer_base' is not a non-static data member of 'timer'
   25 |   timer(int x) : timer_base<false>(3) {}
      |                  ^~~~~~~~~~
<source>:25:28: error: expected '(' before '<' token
   25 |   timer(int x) : timer_base<false>(3) {}
      |                            ^
      |                            (
<source>:25:28: error: no matching function for call to 'timer_base::timer_base()'
<source>:19:3: note: candidate: 'template<bool Bool> timer_base::timer_base(int)'
   19 |   timer_base(int x) {
      |   ^~~~~~~~~~
<source>:19:3: note:   template argument deduction/substitution failed:
<source>:25:28: note:   candidate expects 1 argument, 0 provided
   25 |   timer(int x) : timer_base<false>(3) {}
      |                            ^
<source>:16:8: note: candidate: 'constexpr timer_base::timer_base(const timer_base&)'
   16 | struct timer_base {
      |        ^~~~~~~~~~
<source>:16:8: note:   candidate expects 1 argument, 0 provided

<source>:16:8: note: candidate: 'constexpr timer_base::timer_base(timer_base&&)'
<source>:16:8: note:   candidate expects 1 argument, 0 provided
<source>:25:28: error: expected '{' before '<' token
   25 |   timer(int x) : timer_base<false>(3) {}

我的理解是,调用timer_base<false>(3)可能是在寻找带有非类型模板参数的模板类,而不是在非模板类中寻找模板构造函数。这个假设正确吗?

有人可以详细说明这个问题并为此提供解决方案。

谢谢。

标签: c++c++11templatesclass-template

解决方案


推荐阅读