简体   繁体   English

模板类成员函数的专业化

[英]specialization of member function of templated class

there: 那里:

What is the result of the following codes? 以下代码的结果是什么?

foo.h foo.h

#include <iostream>

template<class _Tp>
struct Foo
{
   void print() { std::cout << "foo\n"; }
};

foo.cxx foo.cxx

#include "foo.h"

template<>
void Foo<int>::print()
{
   std::cout << "foo<int>\n";
}

main.cxx main.cxx

#include "foo.h"

int main()
{
   Foo<double>().print();
   Foo<int>().print();
   return 0;
 }

The results are different: 结果是不同的:

  1. when complied by MSVC, 由MSVC编译时,

     foo foo 
  2. when compiled by g++, 用g ++编译时,

     foo foo<int> 

I would like to get the second result regardless of compilers. 无论编译器如何,我都希望获得第二个结果。 What should I do additionally to achieve? 我还应该做什么? If possible, would you give me an explanation about underlying standards or mechanism. 如果可能的话,请您给我解释一下潜在的标准或机制。 Thank you! 谢谢!

Your program has undefined behavior. 您的程序具有未定义的行为。

There are two implementations of Foo<int>::print() -- an inline definition that is obtained from the class template definition and the non-inline definition in foo.cxx. Foo<int>::print()有两种实现-从类模板定义和foo.cxx中的非内联定义获得的内联定义。 A compiler is free to choose either. 编译器可以自由选择。

A compiler is not required to diagnose that as a problem. 不需要编译器将其诊断为问题。 Many of them (apparently that includes g++ and MSVC) choose that route for definitions of class templates and their member functions. 它们中的许多(显然包括g ++和MSVC)都选择了用于定义类模板及其成员函数的途径。

To make sure that both compilers choose the implementation in foo.cxx, declare the function in foo.h. 为了确保两个编译器都选择foo.cxx中的实现,请在foo.h中声明该函数。

#include <iostream>

template<class _Tp>
struct Foo
{
   void print() { std::cout << "foo\n"; }
};

template<> void Foo<int>::print();

It is interest. 这很有趣。 I know that templates are interpreted at compile time, not link time. 我知道模板是在编译时而不是链接时解释的。 So, in my opinion, specialization template should implements at each cpp files. 因此,我认为,专业化模板应在每个cpp文件中实现。 What is your g++ version? 您的g ++版本是什么?

If the foo.h looks like following, both compilers produce the same results. 如果foo.h如下所示,则两个编译器将产生相同的结果。 But I don't know why. 但是我不知道为什么。

#include <iostream>


template<class _Tp>
struct Foo
{
   void print();
};

template<class _Tp>
void Foo<_Tp>::print()
{
   std::cout << "foo\n";
}

template<> void Foo<int>::print();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM