这个问题需要很长时间,但请耐心等待。
考虑以下文件:
Type1.hpp
#ifndef TYPE1_HPP
#define TYPE1_HPP
struct Type1
{
int a;
int b;
};
#endif
Type2.hpp
#ifndef TYPE2_HPP
#define TYPE2_HPP
struct Type2
{
int c;
int d;
};
#endif
MyTemplate.hpp
#ifndef MYTEMPLATE_HPP
#define MYTEMPLATE_HPP
template <typename T>
struct MyTemplate
{
T t;
};
#endif
Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
struct Type1;
struct Type2;
template <typename T> struct MyTemplate;
int func(const MyTemplate<Type1>& param);
int func(const MyTemplate<Type2>& param);
#endif
Functions.cpp
#include "Functions.hpp"
#include "MyTemplate.hpp"
#include "Type1.hpp"
#include "Type2.hpp"
int func(const MyTemplate<Type1>& param)
{
return param.t.a + param.t.b;
}
int func(const MyTemplate<Type2>& param)
{
return param.t.c - param.t.d;
}
的main.cpp
#include "Functions.hpp"
#include "MyTemplate.hpp"
#include "Type1.hpp"
#include <iostream>
int main()
{
MyTemplate<Type1> x;
x.t.a = 1;
x.t.b = 2;
int y = func(x);
std::cout << y << std::endl;
}
使用Clang编译时:
clang++-3.6 -o testover -std=c++11 -Wall main.cpp Functions.cpp
导致编译错误:
In file included from main.cpp:2:
./MyTemplate.hpp:7:7: error: field has incomplete type 'Type2'
T t;
^
main.cpp:12:18: note: in instantiation of template class 'MyTemplate<Type2>' requested here
int y = func(x);
^
./Functions.hpp:5:8: note: forward declaration of 'Type2'
struct Type2;
^
1 error generated.
当Functions.hpp和cpp中的第二个函数名称更改为func2
时,代码将编译。
我的问题是:与具有不同名称的两个函数相比,为什么编译器需要使用重载函数的不同信息?