简体   繁体   English

使用模板…我的代码有什么问题?

[英]Using templates… What's wrong with my code?

I just recently was learning templates in C++. 我最近是在学习C ++模板。 But I got 3 errors even when I do everything exactly like in my course. 但是,即使我按照自己的方式做所有事情,也遇到了3个错误。

This is the main.cpp: 这是main.cpp:

#include <iostream>
#include "szablony.h"

using namespace std;

int main()
{
    cout << nmax<int>(55,402) << endl;

    Klasa<double> a1;
    a1.ustaw(25.54);

    Klasa<double> a2;
    a2.ustaw(44.55);

    cout << a1.podaj() << " :max: " << a2.podaj() << " = " <<
    nmax<Klasa>(a1.podaj(),a2.podaj()) << endl;

}

And this is "szablony.h": 这是“ szablony.h”:

#include <iostream>

using namespace std;

template <typename T> class Klasa
{
    T wartosc;

public:

    template <typename U> T podaj()
    {
        return (this -> wartosc);
    }

    template <typename U> void ustaw(U war)
    {
        wartosc=war;
    }
};

template <typename T, typename T1, typename T2> T nmax(T1 n1, T2 n2)
{
    return (n1 > n2 ? n1 : n2);
}

template <> Klasa nmax<Klasa>(Klasa n1, Klasa n2)
{
    return (n1.podaj() > n2.podaj() ? n1 : n2);
}

So these are the errors: 所以这些是错误:

  1. "szablony.h":|line 27|error: invalid use of template-name 'Klasa' without an argument list| “ szablony.h”:|第27行|错误:模板名称'Klasa'的无效使用,而没有参数列表|

  2. main.cpp|line 16|error: no matching function for call to 'Klasa::podaj()'| main.cpp |第16行|错误:没有匹配函数可调用'Klasa :: podaj()'|

  3. main.cpp|line 17|error: no matching function for call to 'Klasa::podaj()'| main.cpp |第17行|错误:没有匹配的函数来调用'Klasa :: podaj()'|

This course is from 2004 btw, that's probably one reason, but even when I look on the internet, everything seems ok... 这门课程来自2004年顺便说一句,这可能是一个原因,但是即使我在互联网上看,一切似乎都还不错。

Thank you in advance :) 先感谢您 :)

The main problem is that Klasa is a template class, but you use it in the specialization of nmax as a regular class. 主要问题是Klasa是模板类,但是在nmax的专业化中将其用作常规类。 In particular, Klasa does not represent a type, but eg Klasa<int> does. 特别地, Klasa不代表类型,但是例如Klasa<int>代表类型。

So either make your function return a template template, or use Klasa<type> 因此,要么使您的函数返回模板模板,要么使用Klasa<type>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM