我有一個模板結構,我想「過載」是這樣的:C++ - 定義聲明之外的模板成員函數
#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"; }
}
它的工作沒有問題。