什麼是第二個括號<>下面的函數模板的原因:函數模板特格式
template<> void doh::operator()<>(int i)
這SO question想出了它被認爲有括號缺失operator()
後,但是我可以找不到解釋。
我明白其中的含義,如果它是形式的專業化類型(完全專業化):
template< typename A > struct AA {};
template<> struct AA<int> {}; // hope this is correct, specialize for int
然而,對於函數模板:
template< typename A > void f(A);
template< typename A > void f(A*); // overload of the above for pointers
template<> void f<int>(int); // full specialization for int
哪裏這個適應這個scenarion?:
template<> void doh::operator()<>(bool b) {}
示例代碼,似乎工作,並沒有給任何華rnings /錯誤(用gcc 3.3.3):
#include <iostream>
using namespace std;
struct doh
{
void operator()(bool b)
{
cout << "operator()(bool b)" << endl;
}
template< typename T > void operator()(T t)
{
cout << "template <typename T> void operator()(T t)" << endl;
}
};
// note can't specialize inline, have to declare outside of the class body
template<> void doh::operator()(int i)
{
cout << "template <> void operator()(int i)" << endl;
}
template<> void doh::operator()(bool b)
{
cout << "template <> void operator()(bool b)" << endl;
}
int main()
{
doh d;
int i;
bool b;
d(b);
d(i);
}
輸出:
operator()(bool b)
template <> void operator()(int i)
上面的雙括號語法很奇怪。通常我看過operator(bool b),但operator()(bool b)如何工作?第一個空()的用法是什麼? – Jimm 2012-01-05 20:30:51
@Jimm方法名是`operator()`,它需要一個參數`bool b` ...這是函數調用操作符。請參閱我的代碼示例中的`main`,`d(b)` – stefanB 2012-01-05 22:00:44