我有 Foo
和 Bar
如下:
Foo.h
#include <list>
using namespace std;
class Foo
{
private:
template <typename BarT>
list<BarT*> barT_lst;
public:
template <typename BarT>
Foo(void);
~Foo(void);
};
Foo.cpp
#include "Foo.h"
template <typename BarT>
Foo::Foo(void)
{
}
Foo::~Foo(void)
{
}
酒吧.h
class Bar
{
public:
Bar(void);
~Bar(void);
};
Bar::Bar(void)
{
}
Bar::~Bar(void)
{
}
和 main()
#include "Foo.h"
#include "Bar.h"
int _tmain(int argc, _TCHAR* argv[])
{
Foo<Bar> foo = Foo<Bar>();
return 0;
}
我使用的是 VC++2008。每次构建项目时,它都会显示错误:
1>------ Build started: Project: Test, Configuration: Debug Win32 ------
1>Compiling...
1>Test.cpp
1>c:\users\duong2179\documents\visual studio 2008\projects\test\test\foo.h(12) : fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'msc1.cpp', line 1411)
1> To work around this problem, try simplifying or changing the program near the locations listed above.
1>Please choose the Technical Support command on the Visual C++
1> Help menu, or open the Technical Support help file for more information
1>Build log was saved at "file://c:\Users\duong2179\Documents\Visual Studio 2008\Projects\Test\Test\Debug\BuildLog.htm"
1>Test - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
这看起来很奇怪。请帮忙!
最佳答案
从编译器获取访问冲突不应该真的发生,升级编译器会很好。
但是您的代码也是非法的。如果你打算写 Foo<Bar> foo;
然后 Foo
需要是模板,例如:
template<typename BarT>
class Foo
{
std::list<BarT *> barT_lst;
public:
Foo();
~Foo();
};
template<typename BarT>
Foo<BarT>::Foo()
{
// constructor code here
}
注意:这个类可能违反了Rule of Three ,你不应该有原始指针的容器,除非这些指针不拥有它们所指向的内容。 (在这种情况下,您不需要析构函数)。
关于c++ - C/C++ 优化编译器因使用模板而损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35932805/