首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模板专门化需求

模板专门化需求
EN

Stack Overflow用户
提问于 2011-08-19 19:09:59
回答 1查看 77关注 0票数 2

这非常简单,我很难弄清楚它实际上是如何使用的,

代码语言:javascript
复制
template<class C>
struct P{
};

template<> 
struct P<int>{};

这种特定的专业化有真正的应用程序吗?

EN

回答 1

Stack Overflow用户

发布于 2011-08-19 19:21:13

虽然您的特定示例似乎不太有趣,但模板专门化被广泛使用。下面是一个例子:

代码语言:javascript
复制
template< class T >
struct StringConverter
{
  static std::string Convert( const T& )
  {
    //do some conversion from T to string using stringstream for instance
    //and return result
  }
}

template<>
struct StringConverter< std::string >
{
  static std::string Convert( const std::string& t )
  {
    //no need for conversion here!
    return t;
  }
}

//usage:
std::string a = StringConverter< int >::Convert( 5 ); //default impl
std::string b = StringConverter< std::string >::Convert( "b" ); //specialized
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7120705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档