为什么未调用的模板类成员*参数*被实例化?

时间:2013-11-06 06:52:22

标签: c++ templates sfinae

这个问题与Why uncalled template class members aren't instantiated?是对立的,作者对某些模板方法没有实例化感到惊讶。

我遇到了相反的问题:当我不期望它们时,我的部分函数会被实例化。采取以下计划:

template <class T> class Foo;

template <class T>
class Bar {
  template <class U> void Baz(typename Foo<T>::X x) {}
};

int main() {
  Bar<int> bar;
}

此程序无法编译并显示错误:

test.cc:6:40: error: implicit instantiation of undefined template 'Foo<int>'
  template <class U> void Baz(typename Foo<T>::X x) {}
                                       ^
test.cc:10:12: note: in instantiation of template class 'Bar<int>' requested here
  Bar<int> bar;
           ^
test.cc:2:26: note: template is declared here
template <class T> class Foo;

但是为什么它试图实例化一个我没有调用的函数的参数?它是一个带有模板参数的模板函数,它无法知道,这使得它实例化函数参数类型变得更加奇怪。

为什么这样做?为什么SFINAE在这里没有帮助我,最坏的情况是不考虑过载?

1 个答案:

答案 0 :(得分:3)

创建模板类的实例时,需要完全定义类。这包括成员函数声明。如果未完全定义其中一个成员函数声明,则该类本身未完全定义。

在这种情况下,Foo<T>::X没有定义,因此Baz函数无法完全声明,并且整个类未完全定义。

相关问题