gpt4 book ai didi

c++ - 为什么未调用的模板类成员 *parameters* 被实例化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:39:54 25 4
gpt4 key购买 nike

这个问题是对立的: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 在这里没有帮助我,最坏的情况是不考虑过载?

最佳答案

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

在这种情况下,Foo<T>::X 没有定义所以 Baz函数不能完全声明,整个类也没有完全定义。

关于c++ - 为什么未调用的模板类成员 *parameters* 被实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19805842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com