在使用GCC 4.7.2和Clang 3.1編譯一些C++ 11代碼時,我碰到了一個問題,Clang沒有設法推導出模板參數GCC成功。 在更抽象的形式,代碼看起來是這樣的:作爲模板參數的可變參數模板:演繹適用於GCC,但不適用於Clang
SRC/test.cc:
struct Element {
};
template <typename T>
struct FirstContainer {
};
template <typename T, typename U = Element>
struct SecondContainer {
};
template <template <typename> class Container>
void processOrdinary(Container<Element> /*elements*/) {
}
template <template <typename, typename> class Container>
void processOrdinary(Container<Element, Element> /*elements*/) {
}
template <template <typename, typename...> class Container>
void processVariadic(Container<Element> /*elements*/) {
}
int main() {
// This function instantiation works in both GCC and Clang.
processOrdinary(FirstContainer<Element>{});
// This function instantiation works in both GCC and Clang.
processOrdinary(SecondContainer<Element>{});
// This function instantiation works in both GCC and Clang.
processVariadic(FirstContainer<Element>{});
// This function instantiation works in both GCC and Clang.
processVariadic<SecondContainer>(SecondContainer<Element>{});
// This function instantiation works in GCC but not in Clang.
processVariadic(SecondContainer<Element>{});
return 0;
}
通過閱讀在§14.3.3實施例和規範的標準的§14.8.2我認爲扣除應該有效,但我不能肯定地說。這是我從大樓得到的輸出:
mkdir -p build-gcc/
g++ -std=c++0x -W -Wall -Wextra -Weffc++ -pedantic -c -o build-gcc/test.o src/test.cc
g++ -o build-gcc/test build-gcc/test.o
mkdir -p build-clang/
clang++ -std=c++11 -Weverything -Wno-c++98-compat -c -o build-clang/test.o src/test.cc
src/test.cc:34:3: error: no matching function for call to 'processVariadic'
processVariadic(SecondContainer<Element>{});
^~~~~~~~~~~~~~~
src/test.cc:21:6: note: candidate template ignored: failed template argument deduction
void processVariadic(Container<Element> /*elements*/) {
^
1 error generated.
make: *** [build-clang/test.o] Fel 1
爲什麼結果不同? GCC是否馬虎,鏗鏘笨拙,我的代碼是否包含未指定的行爲或全部?
我同意你的意見。我在C++ 11最終草稿中看到的所有內容都表明這應該起作用。 14.3.3.3尤其相關。 –
你的例子缺少'typedef int Element;',對吧? – Quuxplusone
不,在代碼的開頭我定義了一個名爲Element的結構體。 – psyill