以下C++代碼不MS的Visual Studio 2010編譯:方法指針模板不編譯
class Foo
{
public:
/// Provides the signature of the methods that can be given to addValueSetListener
template <typename TT>
struct ChangeHandler
{
typedef void (TT::* OnSetValueMethod)();
};
template <typename TT>
void bar_ok(TT*, void (TT::*)(), bool = false) {}
template <typename TT>
void bar_ok(const char*, TT*, void (TT::*)()) {}
template <typename TT>
void bar_fails(TT*, typename ChangeHandler<TT>::OnSetValueMethod, bool = false) {}
template <typename TT>
void bar_fails(const char*, TT*, typename ChangeHandler<TT>::OnSetValueMethod) {}
void testBar() {}
};
int main()
{
Foo foo;
foo.bar_ok ("allo",& foo, & Foo::testBar); // compiles
foo.bar_fails("allo",& foo, & Foo::testBar); // compile ERROR
}
編譯器誤差爲'TT': must be a class or namespace when followed by '::'
,用於ERROR線。
失敗的行和唯一不同的行之間的唯一區別是bar_fails通過「模板化typedef」聲明「方法指針類型」參數void (TT::*)()
,而bar_ok直接聲明它。
請注意,如果沒有const char*
的超載,模板化的typedef可以正常工作。在const char *過載可用的情況下,編譯器錯誤地選擇了bar_fails的重載,但它正確地選擇了bar_ok的TT = Foo重載。當typedef適用於像TT *或float *這樣的「簡單」數據時,不會出現此問題。
您標記爲'// compiles'的行沒有辦法。所有這些成員都是「私人」的開始。你能告訴我們真實的代碼嗎? –
'main'也返回'int' ...(看起來是拼寫錯誤) –
@PierreFourgeaud對不起,我修復了這個問題 – Schollii