Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
何时使用c++;模板? 现在我正在学习C++,现在我知道了模板的基本概念, 就像泛型一样, 我发现几乎所有的C++程序都使用模板, 所以我真的想知道我们什么时候应该使用模板? 有人能总结一下你的C++模板吗? 什么时候考虑使用模板?< /P>_C++_Templates - Fatal编程技术网

何时使用c++;模板? 现在我正在学习C++,现在我知道了模板的基本概念, 就像泛型一样, 我发现几乎所有的C++程序都使用模板, 所以我真的想知道我们什么时候应该使用模板? 有人能总结一下你的C++模板吗? 什么时候考虑使用模板?< /P>

何时使用c++;模板? 现在我正在学习C++,现在我知道了模板的基本概念, 就像泛型一样, 我发现几乎所有的C++程序都使用模板, 所以我真的想知道我们什么时候应该使用模板? 有人能总结一下你的C++模板吗? 什么时候考虑使用模板?< /P>,c++,templates,C++,Templates,补充: 如果我们定义了这样的函数 template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b); } 模板 myType GetMax(myType a、myType b){ 返回(a>b?a:b); } 但是我们想要传递一个对象(自定义类)进行比较,我们如何实现呢 补充2: 在下面的答案中,有人编写了这个示例代码 template <class myType> co

补充: 如果我们定义了这样的函数

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}
模板
myType GetMax(myType a、myType b){
返回(a>b?a:b);
}
但是我们想要传递一个对象(自定义类)进行比较,我们如何实现呢

补充2: 在下面的答案中,有人编写了这个示例代码

template <class myType>
const myType& GetMax (const myType& a, const myType& b) {
    return (a<b?b:a);
}

template <class myType, class Compare>
const myType& GetMax (const myType& a, const myType& b, Compare compare) {
    return (compare(a,b)?b:a);
}
模板
常量myType和GetMax(常量myType和a、常量myType和b){

return(a如果您不知道变量的类型,或者您想对许多类型的变量执行相同的操作,您可以使用模板

如果要添加2 int,则需要获取一个int作为返回值 如果您想添加2个double,您需要获得一个double作为返回


因此,基本上,当您想要创建一个泛型类来处理多种类型的类的解决方案,而不必为所有您想要支持的类创建一个父类时,您就可以使用这个模板

您可以只给出您想要使用的类(最好的例子是一个容器,它可以存储您在创建过程中传递的任何类型)

/----容器
模板
类堆栈
{
公众:
T*stackPtr;
}
//-----范例
void main()
{
类型定义堆栈浮动堆栈;
typedef-Stack-IntStack;
}

现在,您可以在同一个类中存储float和int,而不必为每种类型编写特定的类。

简短回答:如果没有用处,请不要。 如果它似乎解决了一个问题(不同类型上的代码重用,…),首先在没有模板的情况下实现和调试,然后添加模板参数


在STL/boost之前,当您需要参数化由类表示的概念时,他们很乐意制作容器。

例如,如果您有一个表示管理对象类型的方法的类

class MyThingManager
{
  void add( MyThing& mything ); 
  //...
};
…可能以后您需要在新类型中使用完全相同的行为,但管理不同的类型。然后您可以选择使用“复制/粘贴/替换”(copy/paste/replace),这将立即导致地狱般的灾难,或者让您的类有一个作为参数管理的类型:

template< class ThingType >
 class ThingManager
    {
      void add( ThingType& thing ); 
      //...
    };
模板
班级事务经理
{
无效添加(物品类型和物品);
//...
};
这样就不会重复代码

另一个问题是,当您希望某个函数调用与任何具有所需语义的参数兼容时:

template< class MyType >
void addPi( MyType& value )
{
    value += PI;
}
模板
void addPi(我的类型和值)
{
值+=PI;
}
这样,您(再次)不必为参数中可能的每种类型重复代码

它不是无缘无故地被称为“泛型编程”

这是简单的例子,但是当你想做一些元编程时,存在更复杂的情况。如果你想去那里,请在写地狱代码之前读至少一本书。我推荐“C++模板元程序”,以及优秀的“现代C++设计”。预订更高级的模板使用,如策略模式和其他众所周知的模板。

G'day

简单的答案是,当您希望行为保持不变,与用于实例化类的类型无关时

因此,整数堆栈的行为方式与浮点堆栈的行为方式与MyClass对象堆栈的行为方式相同

当您希望允许行为的专门化时,可以使用继承和基类

假设有一个名为Animal的基类,它有一个名为makeSound()的成员函数。您不知道每个动物会发出哪些声音,因此您将makeSound成员函数设置为虚拟函数。事实上,由于所有动物都没有默认声音,因此您不知道默认行为是什么,因此您将此成员函数声明为纯虚拟函数

然后,这会告诉任何创建派生类(例如Lion类)实例的人,他们必须提供一个实现makeSound成员函数,该函数将以某种方式提供roar

编辑:我忘了补充一下,这是Scott Meyers的优秀著作《高效C++》(Effective C++)中的一篇文章,我极力推荐这本书


干杯,回答第二个问题( 但是我们想要传递一个对象(自定义类)进行比较,我们如何实现?)

如果要在模板函数中使用自己的类,请使用 操作员>。 您的类只需要定义此运算符或函数

重要的是,您的类需要定义相同的 模板使用的运算符或函数


/Tobias

模板提供了对编译时已知数量进行参数化的方法。请注意,它可以是一种类型(std::vector将只包含整数),但也可以是值:

template <int N, typename T > class MyType
模板类MyType
在整数和类型上模板化,MyType将是与MyType不同的类型

此外,模板允许模板元编程:即编译器在编译时执行程序。Erwin Unruh提供了一个有趣的例子,用于在编译时计算素数


查看一些历史记录。

Re:supplement。如果要传递比较函数,可以提供另一个重载:

template <class myType>
const myType& GetMax (const myType& a, const myType& b) {
    return (a<b?b:a);
}

template <class myType, class Compare>
const myType& GetMax (const myType& a, const myType& b, Compare compare) {
    return (compare(a,b)?b:a);
}
模板
常量myType和GetMax(常量myType和a、常量myType和b){

return(a)或您的函数将导致编译错误。

在您提供的示例中,只要为要比较其实例的数据类型定义了
运算符>
,一切都正常

例如,如果定义以下类:

class fraction
{
private:
    int _num, _den;

public:
    fraction(int num, int den)
    {
        if (den >= 0)
        {
            _num = num;
            _den = den;
        }
        else
        {
            _num = -num;
            _den = -den;
        }
    }

    fraction(const fraction &f)
    {
        _num = f._num;
        _den = f._den;
    }

    bool operator > (const fraction &f) const
    {
        return (_num * f._den) > (f._num * _den);
    }

    bool operator == (const fraction &f) const
    {
        return (_num * f._den) == (f._num * _den);
    }
};
然后可以将模板函数用于此类的实例<
bool c_strings_less(const char* a, const char* b)
{
    return std::strcmp(a, b) < 0; //is a less than b
}

const char* greater = GetMax("hello", "world", c_strings_less);
class fraction
{
private:
    int _num, _den;

public:
    fraction(int num, int den)
    {
        if (den >= 0)
        {
            _num = num;
            _den = den;
        }
        else
        {
            _num = -num;
            _den = -den;
        }
    }

    fraction(const fraction &f)
    {
        _num = f._num;
        _den = f._den;
    }

    bool operator > (const fraction &f) const
    {
        return (_num * f._den) > (f._num * _den);
    }

    bool operator == (const fraction &f) const
    {
        return (_num * f._den) == (f._num * _den);
    }
};
int main(int argc, char* argv[])
{
    fraction a(1,2); // 0.5
    fraction b(3,4); // 0.75
    assert(GetMax/*<fraction>*/(a,b) == a);
    return 0;
}