专门模板化的模板化功能?

时间:2018-02-01 23:57:43

标签: c++

我有一个功能:

// 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。这可能吗?

1 个答案:

答案 0 :(得分:3)

您无法部分专门化功能模板。

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

template <typename> struct Aux;

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

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

这样你只有一个单一的功能模板,选择正确的专业化的所有细节都在类模板中完成,你可以根据你的选择自由地专门化或专门化。

相关问题