相关疑难解决方法(0)

即使不调用它,编译器也会在模板类中实例化该函数

我有一个错误的看法,即a中的template函数class只有在被调用时才被实例化.请参阅以下简单代码:

template<typename T>
struct A
{
  T *p; 
  T& operator * () { return *p; }
};

int main ()
{
  A<int> ai;   // ok
  int i = *ai;  // works fine
  A<void> av;  // compiler complains even "*av" is not called
}
Run Code Online (Sandbox Code Playgroud)

在声明时A<void>,编译器错误如下:

error: forming reference to void
Run Code Online (Sandbox Code Playgroud)

我试图void在模板外部专门化函数,如下所示:

template<>
void A<void>::operator * () {}
Run Code Online (Sandbox Code Playgroud)

但它没有帮助,并给出错误:

error: no member function ‘operator*’ declared in ‘A<void>’
Run Code Online (Sandbox Code Playgroud)

有没有办法用C++ 03解决这个问题?

c++ templates compiler-errors instantiation

1
推荐指数
1
解决办法
162
查看次数

标签 统计

c++ ×1

compiler-errors ×1

instantiation ×1

templates ×1