我有一个模板结构,我想像这样“重载”:
#include <iostream>
template <typename T, typename U = int>
struct foo {
void operator()(T, U);
}
template <typename T, typename U = int>
void foo::operator()(T a, U b){
std::cout << "T, U ()\n";
}
template <typename T>
struct foo<T, int> {
void operator()(T);
}
template <typename T>
void foo<T, int>::operator()(T a){
std::cout << "T ()\n";
}
int main(int argc, char **argv){
foo<int> a;
foo<int, char> b;
a(1);
b(2, 'b');
return false;
}
但是在编译时出现以下错误:
($ g++ test.cpp -o test)
test.cpp:11:6: error: 'template<class T, class U> struct foo' used without template parameters
test.cpp:11:30: error: 'void operator()(T, U)' must be a nonstatic member function
这很奇怪,因为 foo< T, int >::operator() 的定义似乎工作得很好。另外,当我像这样定义内联函数时:
template <typename T, typename U = int>
struct foo {
void operator()(T a, U b){ std::cout << "T, U ()\n"; }
}
它可以正常工作。