我是C++和模板的新手,我遇到了這個問題。我有一個關於這個實現的C++ 11 is_same功能,由德克Holsopple這裏寫的問題:https://stackoverflow.com/a/13071396/5199724C++模板:何時將模板參數包含在模板化的結構中?
這是他的代碼,編譯:
1 template<class T, class U>
2 struct is_same {
3 enum { value = 0 };
4 };
5
6 template<class T>
7 struct is_same<T, T> {
8 enum { value = 1 };
9 };
我的問題是,這是爲什麼不有效:
1 template<class T, class U>
2 struct is_same<T, U> { // template parameters in struct declaration -- not valid?
3 enum { value = 0 };
4 };
5
6 template<class T>
7 struct is_same<T, T> {
8 enum { value = 1 };
9 };
的模板參數在這兩個結構聲明納入將使直觀的感覺來了我,但第二個代碼塊給我在Visual Studio中的以下錯誤:
error C2143: syntax error : missing ';' before '<'
error C2059: syntax error : '<'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
error C3412: cannot specialize template in current scope
那麼爲什麼模板參數需要在第7行而不是在第2行?何時包含模板參數的一般規則是什麼?謝謝你的幫助!