【发布时间】:2015-02-26 18:30:02
【问题描述】:
我正在尝试编写一个函数模板来推断其大部分参数,以实现简单的查找表。
但是,我的努力始终出现编译器错误。 这是我迄今为止最好的尝试:
// A simple templated struct that maps one key to one value
template<typename KT, typename VT>
struct LookupTable
{
KT key;
VT value;
};
// A lookup function that searches an array for a match.
// returns NULL if key was not found.
// returns pointer to matching value when key is found.
//
// The first parameter is a Reference to an Array of T, with a specific size N
// In this example, the size is 12.
template<typename T, size_t N, typename KT, typename VT>
VT* Find(T<KT,VT> (&A)[N], KT key) // <== Multiple Errors on this line
{
VT* pFoundValue = NULL;
for (size_t i = 0; i < N; ++i)
{
if (key == A[i].key)
{
pFoundValue = &(A[i].value);
break;
}
}
return pFoundValue;
}
// Test the function with a simple example
int main(void)
{
LookupTable<std::string, int> calendar[] = {
{ "January", 31 },
{ "February", 28 },
{ "March", 31 },
{ "April", 30 },
{ "May", 31 },
{ "June", 30 },
{ "July", 31 },
{ "August", 31 },
{ "September", 30 },
{ "October", 31 },
{ "November", 30 },
{ "December", 31 }
};
const int* pDays = Find(calendar, std::string("May"));
if (pDays == NULL)
{
cout << "Invalid Month" << endl;
}
else
{
cout << "The month of May has " << *pDays << " Days" << endl;
}
_getch();
return 0;
}
我得到的错误都在Find函数的声明上
(标有注释):
1>error C2143: syntax error : missing ')' before '<'
1>error C2143: syntax error : missing ';' before '<'
1>error C2988: unrecognizable template declaration/definition
1>error C2059: syntax error : '<'
1>error C2059: syntax error : ')'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
看来我已经使所有参数都易于从函数调用中推断出来。
我是否有遗漏的语法错误?
【问题讨论】:
-
T作为模板模板参数,所以声明为:templateclass T
标签: c++ templates type-inference