c++ - 从派生类调用非模板类中的模板构造函数
问题描述
我有一个具有模板构造函数的非模板基类。在派生类中,我试图在成员初始化列表中调用基类构造函数,但它在编译器错误中失败。
#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)
可能是在寻找带有非类型模板参数的模板类,而不是在非模板类中寻找模板构造函数。这个假设正确吗?
有人可以详细说明这个问题并为此提供解决方案。
谢谢。
解决方案
推荐阅读
- android - 为什么 DJI Mobile SDK 需要 Android 物理设备,而不能与 Android 虚拟机配合使用?
- haskell - 将 Haskell 函数“分解”为具有各种中间类型的两个函数时如何避免重复?
- xquery - Xquery 无法将 XML HTTP 内容作为 XML 文档访问
- uwp - UWP:退出UWP-App并启动Win IoT core App
- python - 将秘密传递给通过 SSH 启动的程序
- php - 循环遍历 Foreach,在 if 语句中调用结果
- javascript - 如何使用 setState() 修改 React Native 中的多维数组?
- javascript - 如何从另一个文件“.txt,.js”导入“var”变量?
- javascript - 在未知位置的特定键上更新 JSON
- html - 自动调整容器高度以适应内容