Search code examples
c++templatesmetaprogrammingnon-type

Methods with non-type template parameters


I was wondering what the proper syntax to create non-type templated class methods. I've tried this, but apparently it does not work:

class A
{
    enum B
    {
        C = 0,
        D
    };
    template <A::B value = A::C>
    int fun();
};

template<A::B value>
int A::fun<A::B::C>()
{
    return 1;
}

template<A::B value>
int A::fun<A::B::D>()
{
    return fun<B>() + 1;
}

What am I doing wrong?


Solution

  • You are attempting to partially specialize function templates, which is not allowed. Here is a compilable snippet:

    class A
    {
        enum B
        {
            C = 0,
            D
        };
        template <A::B value = A::C>
        int fun();
    };
    
    template<>
    int A::fun<A::B::C>()
    {
        return 1;
    }
    
    template<>
    int A::fun<A::B::D>()
    {
        return fun<B::C>() + 1;
    }