如何在没有参数的情况下专门化模板类?

LmT*_*oon 1 c++ templates

我有这样的代码,但是编译器说,有关错误(错误C2913:明确的专业化;"向量"不是一个类模板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;
}
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 7

您无法创建Vector没有模板参数的特化,因为Vector至少需要一个.

您可以做的是声明主模板采用任意数量的模板参数,然后将这两种情况定义为特化:

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

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

template <>
class Vector<>
{
    //...
};
Run Code Online (Sandbox Code Playgroud)

  • 因为如果你没有,'Vector`是一个类模板,*需要*至少一个模板参数.使用主模板,`Vector`是一个类模板,它可以包含任意数量的模板参数,并且当没有任何模板参数时,以及当存在至少一个时,存在特化. (3认同)