繁体   English   中英

专门针对模板类型的模板函数?

[英]Specializing templated function for a templated type?

我有一个功能:

// declaration of random, specialize this to provide random instances of types
template <typename T> T random() {
    static_assert(
        std::is_void<T>::value && false, "random() not implemented for type"
    );
}

我想专门针对另一种也已模板化的_point1d类型:

template <typename T>
struct _point1d {
    _point1d(T x) : x(x) {}
    T x;
};

我尝试了这个:

template <typename T>
_point1d<T> random<_point1d<T>>() { return _point1d<T>(random<T>()); }

但是我得到:

error: non-type partial specialization ‘random<_point1d<T> >’ is not allowed

与gcc。 这可能吗?

您不能部分专门化功能模板。

标准解决方案是使用中间帮助程序类模板:

template <typename> struct Aux;

template <typename U> struct Aux<_point1d<U>>
{
    static _point1d<U> f() { /* ... */ }
};

template <typename T> T random() { return Aux<T>::f(); }
//                                 ^^^^^^^^^^^^^^^^^^^

这样,您只有一个单一的功能模板,并且选择正确的专业化的所有详细信息都在类模板内完成,您可以根据需要自由地部分或显式地进行专业化。

暂无
暂无

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

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