Partial specialisation of member function with non-type parameter

北城余情 提交于 2019-12-04 03:20:18

You can wrap the function inside a class.

Only classes, not functions, may be partially specialized.

template<typename T, int R>
struct foo
{
    foo(const T& v) :
        value_(v)
    {}

    void bar()
    {
        return bar_impl< T, R >::bar( * this );
    }

    friend struct bar_impl< T, R >;

    T value_;
};

template< typename T, int R >
struct bar_impl {
    static void bar( foo< T, R > &t ) {
        std::cout << "Generic" << std::endl;
        for (int i = 0; i < R; ++i)
            std::cout << t.value_ << std::endl;
    }
};

template<>
struct bar_impl<float, 3> {
static void bar( foo< float, 3 > &t ) {
    std::cout << "Float" << std::endl;
    for (int i = 0; i < 3; ++i)
        std::cout << t.value_ << std::endl;
}
};

template<int R>
struct bar_impl<double, R> {
static void bar( foo< double, R > &t ) {
    std::cout << "Double" << std::endl;
    for (int i = 0; i < R; ++i)
        std::cout << t.value_ << std::endl;
}
};

Partial specialization is possible only for the full class, not a member function. So you need

template<int R>
struct foo<double, R>
{
    foo(const double& v) :
        value_(v)
    {}

    void bar()
    {    
       std::cout << "Double" << std::endl;
       for (int i = 0; i < R; ++i)
          std::cout << value_ << std::endl;
    }

    double value_;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!