C++ Template Specialization with Constant Value

c++, template-specialization, templates

Solution

I think this might work:

#include <iostream>

template <typename A, size_t B>
class Example {
public:
    Example()
    {
        Construct<B>(identity<A, B>());
    }

    A foo()
    {
        return foo<B>(identity<A, B>());
    }

private:
    template <typename A, size_t B>
    struct identity {};

    template <size_t B>
    void Construct(identity<A, B> id)
    {
        for (size_t i = 0; i < B; ++i)
        {
            value[i] = 0;
        }
        std::cout << "default constructor\n";
    }

    template <size_t B>
    void Construct(identity<A, 2> id)
    {
        value[0] = 0;
        value[1] = 0;
        std::cout << "special constructor\n";
    }

    template <size_t B>
    A foo(identity<A, B> id)
    {
        A r = 0;
        for (size_t i = 0; i < B; ++i)
        {
            r += value[i];
        }
        std::cout << "default foo\n";
        return r;
    }

    template <size_t B>
    A foo(identity<A, 2> id)
    {
        std::cout << "special foo\n";
        return value[0] + value[1];
    }

    A value[B];
};

int main()
{
    Example<int, 2> example; // change the 2 to see the difference
    int n = example.foo();
    std::cin.get();
    return 0;
}

Sorry, I just copy and pasted it from my test project. It's not really "specialization" in a way, it just calls overloads to specialized functions. I'm not sure if this is what you want and imo this isn't very elegant.

Problem

Is there a straightforward way for defining a partial specialization of a C++ template class given a numerical constant for one of the template parameters? I'm trying to create special constructors for only certain kinds of template combinations: ``` template <typename A, size_t B> class Example { public: Example() { }; A value[B]; }; template <typename A, 2> class Example { public: Example(b1, b2) { value[0] = b1; value[1] = b2; }; }; ``` This example won't compile, returning an error `Expected identifier before numeric constant` in the second definition. I've had a look through a number of examples here and elsewhere, but most seem to revolve around specializing with a type and not with a constant. Edit: Looking for a way to write a conditionally used constructor, something functionally like this: ``` template <typename A, size_t B> class Example { public: // Default constructor Example() { }; // Specialized constructor for two values Example<A,2>(A b1, A b2) { value[0] = b1; value[1] = b2; }; A foo() { A r; for (size_t i = 0; i < b; ++b) r += value[i]; return r; } // Hypothetical specialized implementation A foo<A, 2>() { return value[0] + value[1]; } A value[B]; }; ```

Original source

Related problems