【发布时间】:2018-10-21 22:02:51
【问题描述】:
我学习了如何使用模板,它可以节省很多时间,但是当我尝试使用带有构造函数的模板时,它会出错,我不知道如何修复错误。
我的项目包含...
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;
}
头文件.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?)
不知何故构造函数不能正常工作,但函数可以。
谁能给我解释一下?
【问题讨论】:
-
该;在 c 类声明的末尾
-
你能标出错误所指的行吗?
-
不确定您对
template<> c::c<c>(const c& input)的期望。 -
你已经有正确的构造函数
template<typename T> c::c(const T& input)。 -
@Jarod42 我知道,但是我想要特定类型的构造函数和函数,例如字符串和自己的类,因为
uint64_t = string会产生错误并且与uint64_t = class相同,所以我创建了特定类型的构造函数和处理它的函数,但只有构造函数才会产生错误
标签: c++ visual-studio templates visual-studio-2017