在处理我的类声明时,我在尝试使用自动类型推导时如何在非类模板中使用别名模板和模板变量有些困惑。
信号.h
#ifndef SIGNAL_H
#define SIGNAL_H
#include <cstdint>
template<typename T>
using TimeSignal = T;
using DiscreteTime = TimeSignal<std::uint8_t>;
using ContinuousTime = TimeSignal<double>;
class Signal {
private:
template<typename T>
static TimeSignal<T> time_;
double voltage_;
double current_;
public:
template<typename T>
explicit Signal( TimeSignal<T> time, double voltage = 0, double current = 0 ) :
voltage_{voltage}, current_{current}
{ time_ = time; }
double sampleVoltage() { return voltage_; }
double sampleCurrent() { return current_; }
template<typename T>
static auto atTime() { return time_; }
};
#endif // SIGNAL_H
我会这样使用它:
#include <iostream>
#include "Signal.h"
int main() {
DiscreteTime t1{ 5 };
ContinuousTime t2{ 7.5 };
Signal s1{ t1, 3.5, 0.05 );
Signal s2{ t2, 4.3, 0.09 );
auto time1 = s1.atTime();
auto time2 = s2.atTime();
return 0;
}
我不想模板这个类,所以我在考虑有一个内部变量模板。在课堂之外,我试图使用模板别名来描述不同的“TimeSignals”,因为“DiscreteTime”通常是描述性的,integral type
并且 aContinousTime
是浮点数或实数集。然而,我正在模板这个类的构造函数,它接受TimeSignal
类型,并希望类根据传入的两种类型中的哪一种来推断或自动解析它的内部变量模板到该类型。最后我试图使用自动类型扣除返回该类型。
我不知道它是语法还是用法,但这让我很难过。我不确定如何使它进入工作编译状态。
这是 Visual Studio 2017 给我的当前编译器错误。
1>------ Build started: Project: Circuit Maker Simulator, Configuration: Debug x64 ------
1>main.cpp
1>c:\...\main.cpp(15): error C2672: 'Signal::atTime': no matching overloaded function found
1>c:\...\main.cpp(15): error C2783: 'auto Signal::atTime(void)': could not deduce template argument for 'T'
1>c:\...\Signal.h(64): note: see declaration of 'Signal::atTime'
1>c:\...\main.cpp(24): error C2672: 'Signal::atTime': no matching overloaded function found
1>c:\...\main.cpp(24): error C2783: 'auto Signal::atTime(void)': could not deduce template argument for 'T'
1>c:\...\Signal.h(64): note: see declaration of 'Signal::atTime'
1>Done building project "Circuit Maker Simulator.vcxproj" -- FAILED.
编译器错误对他们所说的很明显,但就像他们在没有任何帮助、帮助或如何解决或解决这个问题的建议的情况下对我尖叫或大喊大叫......
编辑
用户rafix07的回答给了我很大的帮助,而且很有帮助。我遗漏了几件事,如果我一直盯着它看足够长的时间,我可能最终会发现其中两件事,那就是在需要它的模板参数或参数的类中使用变量模板。另一种是在主函数中使用范围解析运算符来调用静态函数。我可以找到他们给一些时间。
让我陷入困境的一个问题是,我必须在调用它时显式地实例化我想要的类型的函数模板。这是让我为我们的头发拔掉头发的那个……
根据他的答案中的链接调整代码后,我现在可以编译,但是我现在收到未解析的外部符号的链接器错误,它与模板变量有关。这应该不是问题,只需要在 cpp 文件中定义它来解析静态变量。