Как создать шаблон конструктора - PullRequest
0 голосов
/ 11 мая 2018

Я узнал, как использовать шаблон, и он может сэкономить много времени, но когда я пытаюсь использовать шаблон с конструктором, он выдает ошибки, и я не знаю, как исправить ошибку.

Мой проект содержит ...

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?)

Каким-то образом конструктор не работает должным образом, но функция работает.

Может кто-нибудь объяснить мне?

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Полагаю, вы просто не можете создавать конструкторы с помощью шаблонов, подумайте над тем, чтобы сделать целый класс шаблонным для конструкторов.

    template <typename T>
    class
    {
       ...
       c<T>() = default; // for example
       c<T>(const c& input) {...}
       ...
    }

    int main()
    {
        c<int>* a = new c<int>();
    }
0 голосов
/ 11 мая 2018

Кажется, вы хотите:

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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...