[英]Does C++ treat an instantiated template class any differently from a non-templated type?
When using virtual functions it is often convenient to use a single class template for both the base class and all derived classes.使用虚函数时,对基本 class 和所有派生类使用单个 class 模板通常很方便。 My question is: are classes defined this way treated any differently by the C++ compiler from the same classes defined without templates?
我的问题是:C++ 编译器以这种方式定义的类与没有模板定义的相同类有什么不同吗?
Here is an example of some classes created using templates:以下是使用模板创建的一些类的示例:
template <typename T=void> struct Adder;
template <> struct Adder <void>
{
virtual double add(double a, double b)
{
return (a+b);
}
};
template <typename T> struct Adder : Adder <void>
{
virtual double add(double a, double b)
{
return ((T)a+(T)b);
}
};
using AdderBase = Adder <void>;
using AdderInt = Adder <int>;
using AdderFloat = Adder <float>;
using AdderDouble = Adder <double>;
int main(int argc, char* argv[])
{
AdderBase* addI = new AdderInt;
AdderBase* addF = new AdderFloat;
AdderBase* addD = new AdderDouble;
printf("addI = %18.1f\n", addI->add(11111111111111111.0, 1.0));
printf("addF = %18.1f\n", addF->add(11111111111111111.0, 1.0));
printf("addD = %18.1f\n", addD->add(11111111111111111.0, 1.0));
}
And here is an example of classes with the same functionality created without templates:下面是一个在没有模板的情况下创建的具有相同功能的类的示例:
struct AdderBase
{
virtual double add(double a, double b)
{
return (a+b);
}
};
struct AdderInt : AdderBase
{
virtual double add(double a, double b)
{
return ((int)a+(int)b);
}
};
struct AdderFloat : AdderBase
{
virtual double add(double a, double b)
{
return ((float)a+(float)b);
}
};
struct AdderDouble : AdderBase
{
virtual double add(double a, double b)
{
return ((double)a+(double)b);
}
};
Does the compiler treat the classes AdderBase, AdderInt, AdderFloat or AdderDouble differently when they are defined in these two different ways?当以这两种不同的方式定义类 AdderBase、AdderInt、AdderFloat 或 AdderDouble 时,编译器是否会以不同的方式处理它们?
An example of a difference might be a different order for overload resolution when the class is used as a parameter in an overloaded function.当 class 用作重载 function 中的参数时,不同的示例可能是重载解析的不同顺序。
The short answer is no.最简洁的答案是不。
In particular, I'd expect any reasonable compiler to generate identical code when you used either of your implementations of (say) AdderFloat
.特别是,当您使用(比如说)
AdderFloat
的任何一个实现时,我希望任何合理的编译器都能生成相同的代码。 In fact, even well before the code generator starts looking at the code, both are doing to be reduced to identical intermediate representations.事实上,甚至在代码生成器开始查看代码之前,两者都在努力简化为相同的中间表示。
There are cases where you can get different code from a template, but most often that's when you know there's a shortcut for some particular type, and write a specialization to let the compiler take advantage of that shortcut for that particular type.在某些情况下,您可以从模板中获取不同的代码,但大多数情况下,您知道某些特定类型有一个快捷方式,并编写一个专门化来让编译器利用该特定类型的快捷方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.