我学会了如何使用模板,它可以节省大量时间,但是当我尝试使用带有构造函数的模板时,它会出错,而且我不知道如何修复错误。
我的项目包含......
的main.cpp
#include "Header.h"
#include <iostream>
using namespace std;
int main(){
c a(1);
c b(a);
a.f(2);
b.f(a);
return 0;
}
Header.h
#pragma once
#include <iostream>
using namespace std;
class c {
public:
template<typename T>
c(const T&);
~c();
template<typename T>
void f(const T&);
private:
uint64_t data;
};
//Constructors
template<typename T>
inline c::c(const T& input) {
data = input;
}
template<>
inline c::c<c>(const c& input) { //This line produced errors
data = input.data;
}
//Destructor
inline c::~c() {}
//Functions
template<typename T>
inline void c::f(const T& input){ //Magic function
cout << (data += input) << endl;
}
template<>
inline void c::f<c>(const c& input){ //Magic function
cout << (data += input.data) << endl;
}
我正在使用Visual Studio 2017,错误是......
C2988 unrecognizable template declaration/definition
C2143 syntax error: missing ';' before '<'
C7525 inline variables require at least '/std:c++17'
C2350 'c::{ctor}' is not a static member
C2513 'c::{ctor}': no variable declared before '='
C2059 syntax error: '<'
C2143 syntax error: missing ';' before '{'
C2447 '{': missing function header (old-style formal list?)
某种方式构造函数不能正常工作,但功能确实如此。
有人可以向我解释一下吗?
答案 0 :(得分:0)
我相信,你不能用模板构造构造函数,考虑使构造函数模仿整个类。
sudo service elasticsearch start
答案 1 :(得分:-2)
似乎你想要:
class c
{
public:
template<typename T>
c(const T&);
c(const c&) = default;
template<typename T>
void f(const T&);
void f(const c&);
private:
uint64_t data;
};
template<typename T>
c::c(const T& input) : data(input) {}
template<typename T>
void c::f(const T& input) { //Magic function
data += input;
std::cout << data << std::endl;
}
inline void c::f(const c& input) { //Magic function
data += input.data;
std::cout << data << std::endl;
}