模板中类型名称分配的目的是什么 [英] what's the purpose of typename assignment inside templates

查看:47
本文介绍了模板中类型名称分配的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到了这段代码(如果要丢失某些内容,我会尝试包括所有详细信息):

I have come across this piece of code (I'm trying to include all details in case I'm missing something):

template< typename TYPE = TYPE_with_an_arbitrarily_long_name,
          typename KIND = KIND_with_an_arbitrarily_long_name>

class Foo
{
public:
    virtual void bar(TYPE& t, KIND& k) = 0;
};

我不了解的部分是模板中的分配:

And the part I don't understand is the assignments inside the template:

template <typename TYPE = TYPE_with_an_arbitrarily_long_name, ..

我一直在试图了解这种效果,但到目前为止我什么都没做.这是我尝试过的一些东西:

I have been trying to understand the effect of this but so far I couldn't produce any. Here are some stuff I have tried:

#include <iostream>
#include <typeinfo>
using namespace std;

template<typename T>
void foo(T t) {
    cout << typeid(t).name() << " ";
}

template<typename T = int>
void bar(T t) {
    cout << typeid(t).name() << " ";
}

template<typename T = double>
void baz(T t) {
    cout << typeid(t).name() << " ";
}

int main()
{
    cout << "\nfoo: ";
    foo(3); foo<int>(3); foo<double>(3);
    cout << "\nbar: ";
    bar(3); bar<int>(3); bar<double>(3);
    cout << "\nbaz: ";
    baz(3); baz<int>(3); baz<double>(3);
    return 0;
}

打印出:

foo: i i d
bar: i i d
baz: i i d

所以我的问题是:

  1. 模板中的赋值有什么作用?
  2. 在上面的示例中使用它的目的是什么?
  3. 没有第三个问题.

感谢您的帮助.

EDIT 结果功能仅适用于c ++ 11

EDIT turned out functions are only compilable with c++11

推荐答案

这称为默认模板参数",用于指定未指定类型时使用的类型-与默认函数参数类似.此技术广泛用于类-查看 std :: vector std :: string ,您将看到它们具有多个默认类型参数.

This is called 'default template argument' and specifies which type is used, when none is specified - alike default function parameters. This technique is widely used for classes - look at definition of std::vector or std::string, and you will see they have multiple default type parameters.

函数模板的默认类型参数的最佳用法是无法从实际参数中轻松推导出类型参数,并且未明确指定类型参数时-编译器将使用默认值.在您的示例中,不需要默认类型,因为可以从实际的调用参数中轻松推导出来.

Best use for default type parameters for function templates is when type argument cannot be easily deduced from actual arguments, and it is not specified explicitly - then compiler will use default one. In your example there is no need for default types, because it can be easily deduced from actual call parameters.

直到C ++ 0x默认类型参数才允许用于类模板-它们不能与功能模板一起使用.使用C ++ 0x,它发生了变化,但是某些较旧的编译器(例如Visual C ++ 2008)不允许您使用它们.

Until C++0x default type parameters were allowed only for class templates - they were not possible to use with function templates. With C++0x it changed, but some older compilers (for example Visual C++ 2008) would not let you to use them.

这篇关于模板中类型名称分配的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆