Template Specialization

转载 2004年09月19日 07:29:00
See this in the MSDN LibrarySee This in MSDN Library

Page Options

Conformance to ISO Standards for C++

Kate Gregory
Gregory Consulting

April 2004

Applies to:
Microsoft® Visual C++® .NET 2003
Microsoft® Visual C++® Toolkit 2003
Microsoft® Visual Studio® .NET

Summary: Demonstrates how Visual C++ can be used to incorporate the .NET Framework into C++ applications. (5 printed pages)

This article is part of a code sample included with the Visual C++ Toolkit 2003, available for download at http://msdn.microsoft.com/visualc/vctoolkit2003.


Template Specialization
The sample
Compiling and running
Related Books

Microsoft® Visual C++® .NET 2003 achieves the highest level of standards-conformation of any release of Visual C++. Visual C++ was first launched in 1993, and the ISO C++ standard dates from 1997. Each release of Visual C++ since the standard has become more compliant, and this release achieves roughly 98% compliance. (No single industry accepted standardized test-suite exists to compare or measure C++ compiler implementations. Three popular suites are Dinkumware, Perennial, and Plum Hall. Visual C++ .NET 2003 was tested against all three).

This high level of compliance enables Visual C++ .NET 2003 to compile popular modern C++ libraries (including LOKI, BOOST, and BLITZ), a feat achieved by few, if any, other compilers.

A vital standard language feature for compiling these libraries is partial template specializtion, which is demonstrated by this sample. Try compiling it with other compilers; Visual C++ 2002, for example, gives error messages and cannot compile it.

Template Specialization

Templates typically define a class or function using one or more placeholders that represent classes or types. At compile time, instantiations of the templates are generated to match the use of the template in your code. For example, this template function can be used to compare integers, floating point numbers, or instances of any class that defines the > operator:

T biggest(T a, T b)
   if (a > b)  return a;
   return b;

You might use this template like this:

int x = biggest(3,4);
double d = biggest(4.1, -2.3);

// SalesRep instances created elsewhere, 
// operator> defined for SalesRep class
SalesRep bestseller = biggest(John, Jane); 

The compiler will generate code for biggest(int,int), biggest(double, double), and biggest(SalesRep, SalesRep), and this code will be linked into your executable.

C++ programmers traditionally run into trouble with templates that need to handle strings. Traditional char* strings can't be compared with > and < (those operators just compare the pointer values, not the strings to which they point), or copied with = the way numbers and objects can. One solution is to write a specialization—an instantiation for a particular type that the compiler will use instead of the more general template. Here is a specialization of biggest() for the char* type:

const char* biggest(const char* a, const char* b)
   if (strcmp(a,b) > 0)  return a;
   return b;

Visual C++ has been able to handle template specialization for a long time. What's new in the 2003 release is the ability to handle partial template specialization. This applies to templates that take two placeholder types, rather than just one as biggest() does.

The Sample

Collection classes are especially likely to use multiple placeholders. A lookup table might hold values (numbers, Employee instances, dates, char* strings) that are indexed by a key that is an integer, a char* string, or a date. The Pair template is a simple class that works with two placeholders:

class Pair
    A index;
    B value;
    Pair(A aa, B bb):index(aa),value(bb) {}
    void display(){cout << index << ' ' << value << endl;}
    bool operator>(const Pair& p) { return index>p.index;}

Pair doesn't do much, but you can imagine that similar code would be at the heart of a flexible collection solution. It holds copies of the index and value, displays them, and can compare two Pair instances by comparing only their indexes. It works flawlessly when the index type, A, is an integer or other numeric type, or a class that has implemented operator >. When the index type is char*, the comparisons become meaningless since > compare the numerical address of the character pointer rather than the characters to which it points. Additionally, the initialization of index will not make a copy of the characters, but only of the pointer.

A partial template specialization is a specialization where one of the placeholders has been replaced with a specific type (char* in this case) but the other has not. For Pair, a partial specialization for char* index values looks like this:

class Pair
    char* index;
    B value;
    Pair(char* aa, B bb):value(bb) {index = new char[strlen(aa)];
    void display() {cout << index << ' ' << value << endl;}
    bool operator>(const Pair& p)
     { return ( strcmp(index,p.index) > 0);}

This code would not have compiled under earlier versions of Visual C++. From Visual C++ .NET 2003 onward, however, it compiles.

Compiling and running

The main() in this sample creates various Pairs and compares them:

int main(int argc, char* argv[])
    Pair first(2.2,3);
    Pair second(2.1,4);
    if (first > second)
        cout << "first is greater" << endl;
        cout << "first is not greater" << endl;
    Pair third("Hello",4);
    Pair fourth("World",5);
    if (third > fourth)
        cout << "third is greater" << endl;
        cout << "third is not greater" << endl;

    return 0;

To compile the sample, use this command line:

cl /EHsc conformance.cpp

To run it:


You should see this output:

2.2 3
2.1 4
first is greater
Hello 4
World 5
third is not greater

The Pair called first is greater because 2.2 is greater than 3. The Pair called third is not greater because "Hello" is not greater than "World".


Partial template specialization is a vital technique for writing rich and useful collections. It can serve a useful purpose in many C++ programs, and is just one of the many new areas of standards conformance in Visual C++ .NET 2003.

For more information about Visual C++ ISO C++ standards conformance see Visual C++ .NET 2003 Enhanced Compiler Conformance.

Related Books

Microsoft Visual C++ .Net 2003 Kick Start by Kate Gregory


C++中的偏特化(partial specialization)

c++中的偏特化的大概意思是:如果某个class template拥有一个以上的template的参数,我们就可以针对其中某个或数个(不实全部)template参数进行特化工作。也就是说,我们可以 在...
  • likun_tech
  • likun_tech
  • 2012年02月24日 20:32
  • 2714

C++学习笔记36 模版的显式具体化(template specialization)和显式实例化(template instantiation)

C++的模版有时候很可能无法处理某些类型。 例如: #include using namespace std; class man{ private: string name; int data...
  • guang_jing
  • guang_jing
  • 2014年08月20日 23:18
  • 56403

Template Specialization and Partial Template Specialization

(1)        类模板特化有时为了需要,针对特定的类型,需要对模板进行特化,也就是特殊处理.例如,stack类模板针对bool类型,因为实际上bool类型只需要一个二进制位,就可以对其进行存储,...
  • rommi
  • rommi
  • 2010年12月03日 13:56
  • 994

specialization of template.... in different namespace的解决

代码来自DTL文档index.htm struct Example { // tablename.columnname: ...
  • coder_xia
  • coder_xia
  • 2011年09月09日 20:08
  • 1487


C++成员函数模板特化问题1.类似代码写法:#include #include class test{public:  template   void print(T t);  template   ...
  • yi_jun_jun
  • yi_jun_jun
  • 2008年09月09日 15:46
  • 3502

template specialization

template specializationtemplate is the fundation of generic programming in c++.template 分为 template ...
  • wengyunhe
  • wengyunhe
  • 2010年06月17日 19:27
  • 262

template specialization on template class

  • wengyunhe
  • wengyunhe
  • 2010年06月17日 19:38
  • 313

linux template error: explicit specialization in non-namespace scope

将Windows上的项目移植到linux上,发现C++ template的实现还是有些不同,总的来说,linux上的template实现和C++标准更一致,而Windows上的实现更宽松。有些细微的不...
  • doubleface999
  • doubleface999
  • 2017年02月19日 09:15
  • 255

模板特化(template specialization)

 模板的特化(template specialization)分为两类:函数模板的特化和类模板的特化。(1)函数模板的特化:当函数模板需要对某些类型进行特别处理,称为函数模板的特化。例如:      ...
  • wangyongyuan
  • wangyongyuan
  • 2009年11月11日 17:43
  • 541

模板特殊化(Template specialization)

http://hi.baidu.com/yzmforever123/item/5ce760521239219408be17a4 模板的特殊化是当模板中的pattern有确定的类型时,模板有一...
  • fingding
  • fingding
  • 2014年06月18日 09:46
  • 1333
您举报文章:Template Specialization