【发布时间】:2013-11-06 06:52:22
【问题描述】:
这个问题与: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 在这里没有帮助我,最坏的情况是从考虑中消除了超载?
【问题讨论】:
-
作为一个数据点,如果函数没有
::X依赖类型,并且只有void Baz(Foo<T> x),则编译时不会尝试实例化Foo。