隐式模板参数 [英] Implicit Template Parameters

查看:113
本文介绍了隐式模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在Xcode中生成编译错误:

The following code generates a compile error in Xcode:

template <typename T>
struct Foo
{
    Foo(T Value)
    {
    }
};

int main()
{
    Foo MyFoo(123);
    return 0;
}

error: missing template arguments before 'MyFoo'

Foo MyFoo(123);更改为Foo<int> MyFoo(123);可以解决此问题,但是编译器不应该能够找出适当的数据类型吗?

Changing Foo MyFoo(123); to Foo<int> MyFoo(123); fixes the issue, but shouldn't the compiler be able to figure out the appropriate datatype?

这是编译器错误,还是我误解了隐式模板参数?

Is this a compiler bug, or am I misunderstanding implicit template parameters?

推荐答案

从理论上讲,构造函数可以推断正在构造的对象的类型,但声明如下:

The constructor could in theory infer the type of the object it is constructing, but the statement:

Foo MyFoo(123);

正在为MyFoo分配临时空间,并且必须知道MyFoo的完全限定类型才能知道需要多少空间.

Is allocating temporary space for MyFoo and must know the fully-qualified type of MyFoo in order to know how much space is needed.

如果要避免键入(即用手指)特别复杂的模板的名称,请考虑使用typedef:

If you want to avoid typing (i.e. with fingers) the name of a particularly complex template, consider using a typedef:

typedef std::map<int, std::string> StringMap;

或者在C ++ 0x中,您可以使用auto关键字来使编译器使用类型推断-尽管许多人认为这会导致可读性更差,更容易出错的代码,其中包括我自己. ; p

Or in C++0x you could use the auto keyword to have the compiler use type inference--though many will argue that leads to less readable and more error-prone code, myself among them. ;p

这篇关于隐式模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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