假设我有一个基本模板功能foo<T>()
,其中包含的完全专业化功能T = int
。基础模板的身体foo<T>()
调用另一个模板,Bar<T>::baz
但foo<int>()
确实没有。
如果foo<int>()
被写入,则如果没有成员,则编译将失败!为什么是这样?我们从不调用基本模板,也不能,因为它被专业化掩盖了!如果从基本模板中删除了对它的引用,则可以确认;编译成功,我们看到确实按预期调用了的专用版本。Bar<int>
baz
Bar
foo()
foo.h
#include <iostream>
template <typename T>
class Bar {};
template <typename T>
void foo(T arg) {
Bar<T>::foo(); // XXX: error; comment to fix
std::cout << "using base template" << std::endl;
}
foo.cpp
#include "foo.h"
template <> void foo<int>(int i) {
std::cout << "specialization" << std::endl;
}
main.cpp
#include "foo.h"
int main(int argc, char **argv) {
int i = 1;
foo<int>(i); // prints "specialization" if noted line is commented
return 0;
}
为什么无法编译?
您会看到此问题,因为专业化放置在其他编译单元或其他.cpp
文件中。放入foo.h
以获得预期的行为。
编辑
对于您在处理多定义问题时的评论问题,请检查以下示例。
您可以将专业化的定义移至.cpp
文件,并将声明保留在头文件中,如下所示:
foo.h
#include <iostream>
template <typename T>
class Bar {};
template <typename T>
void foo(T arg) {
Bar<T>::foo();
std::cout << "using base template" << std::endl;
}
template <>
void foo<int>(int i); // declaration
foo_int.cpp
#include "foo.h"
template<>
void foo<int>(int i)
{
std::cout << "specialization" << std::endl;
}
main.cpp
#include "foo.h"
void something();
int main(int argc, char **argv) {
int i = 1;
foo<int>(i);
something();
return 0;
}
something.cpp
#include "foo.h"
void something() {
int i = 1;
foo<int>(i);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句