Alex Aparin
Alex Aparin

Reputation: 4512

How to specialize template class without parameters?

I have such code, but compiler says about error (error C2913: explicit specialization; 'Vector' is not a specialization of a class template d:\test_folder\consoleapplication1\consoleapplication1\consoleapplication1.cpp 28 1 ConsoleApplication1 ):

#include <iostream>

template <int N, int ... T>
class Vector
{
public:
    static void print_arguments(void)
    {
        std::cout << N << " : " << std::endl;
        Vector<T>::print_argumetns();
    }
protected:
private:
};

template <>
class Vector<>
{
public:
    static void print_arguments(void)
    {
    }
protected:
private:
};

int main(void)
{
   std::cout << "Hello world" << std::endl;
   int i = 0;
   std::cin >> i;
   return 0;
}

Upvotes: 2

Views: 906

Answers (2)

EmDroid
EmDroid

Reputation: 6066

What you probably want is this:

template <int N, int ... T>
class Vector
{
public:
    static void print_arguments(void)
    {
        std::cout << N << " : " << std::endl;
        Vector<T...>::print_arguments();
    }
protected:
private:
};

template <int N>
class Vector<N>
{
public:
    static void print_arguments(void)
    {
        std::cout << N << " : " << std::endl;
    }
protected:
private:
};

The second is a "terminating" partial specialization, which is used when only one parameter is used.

Upvotes: 0

TartanLlama
TartanLlama

Reputation: 65600

You can't create a specialization of Vector with no template parameters, because Vector requires at least one.

What you can do instead is declare the primary template to take any number of template arguments, then define both cases as specializations:

//primary template
template <int... Ns>
class Vector;

//this is now a specialization
template <int N, int ... T>
class Vector<N,T...>
{
    //...
};

template <>
class Vector<>
{
    //...
};

Upvotes: 9

Related Questions