类与模板成员函数,是同一个类吗? [英] Class with templated member function, is the same class?

查看:130
本文介绍了类与模板成员函数,是同一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对模板成员函数有些困惑,让我们假设我们有一个模糊的成员函数的奇怪的结构,例如:

I'm a bit confused about templated member functions, let's suppose that we have some weird struct with a templated member function, like this:

struct Foo
{
    template <typename T> void f(T t) {};
};

然后,我们将该结构存储到一些标准容器中:

And then, we store that struct into some standard container:

std::vector<Foo> V;

V.push_back(Foo());
V.push_back(Foo());
V.push_back(Foo());
V.push_back(Foo());

让我们调用模板成员函数的不同实例:

Next; let's call different instances of the templated member function:

V.at(0).f<int>(1);
V.at(0).f<char>(2);
V.at(1).f<float>(3.4f);
V.at(2).f<double>(5.6);
V.at(3).f<long>(7);

最后,问题:

似乎答案是肯定的,但...第一个Foo实例在结束时有两个重载的f成员函数:

¿All the instances of Foo class are from the same class? it seems that the answer is yes but... the first Foo instance has at the end two overloads of the f member function:

[0] Foo::f(int t);
[0] Foo::f(char t);

另一方面,其他Foo实例似乎只有一个版本的f函数。因此显然每个实例的基本类型因成员函数的不同而不同。

And in the other hand, the other Foo instances seems to have only one version of the f function. So apparently the base type of each instance is different due the differences on member functions.

[1] Foo::f(float t);
[2] Foo::f(double t);
[3] Foo::f(long t);

?f函数在哪里实例化?显然我们可以得到地址的Foo :: f(int t)函数只从第一个Foo实例,因为那个函数只属于那个实例;

¿Where the f functions are instanced? apparently we can get the address of the Foo::f(int t) function only from first Foo instance, because that function only belongs to that instance; same for the other functions.

推荐答案

所有的重载都是由编译器为 Foo :: f 成员函数生成的,你可以认为它已经用手写出了所有的。

All the overloads are generated by the compiler for the Foo::f member function, you can think of it as having written all of them out by hand.

重载生成(模板实例化)不是基于实例的,而是基于类的,类本身获取所有模板实例化splatted (就像在类的正文中写了所有不同类型的重载,对于给定的类型T)

The overload generation (template instantiation) is not instance based, but rather it is class based, the class itself gets all the template instantiations splatted (just like having written all the overloads of the different types in the body of the class, for the given type T)

所以在你的情况下:

struct Foo 
{     
   template <typename T> void f(T t) {}; 
}; 

会成为(概念上的)

struct Foo 
{     
   void f<int>(int t) {}; 
   void f<char>(char t) {}; 
   void f<float>(float t) {}; 
   ...
   /// all the other uses of f with different types, anywhere in your code.
}; 

这是人们反对模板的原因之一,它被称为代码膨胀。

This is one of the reasons people argue against templates, it's called "code bloat".

这篇关于类与模板成员函数,是同一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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