开发者

Explicit function template specialization

I th开发者_如何学运维ought that template specializations were fully independent entities and could have whatever they wanted. But VC++ threw me an error when I made the return type of a specialization different to the return type of the original template. Is that really Standard? I worked around it easily by moving the function body into a static class.


There is no function template partial specialization, because there's overloading of functions (and function templates. However, function overloading is much more limited than template specialization, so what you usually do, is to fall back on class template specializations:

template< typename R, typename T >
struct foo_impl {
  static R foo(T)
  {
    // ...
    return R();   // blah
  }
};

template< typename T >
struct foo_impl<void,T> {
  static void foo(T)
  {
    // ...
  }
};

template< typename R, typename T >
R foo(T obj);
{
  return foo_impl<R,T>::foo(obj);  // fine even if R is void
}


Function specialization is weird and almost non-existent. It's possible to fully specialize a function, while retaining all types - i.e. you're providing a custom implementation of some specialization of the existing function. You can not partially specialize a templated function.

It's likely that what you're trying to do can be achieved with overloading, i.e.:

template <typename T> T foo(T arg) { return T(); }
float foo(int arg) { return 1.f; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜