Visual Studio 2015更新3改进了对C 11的支持,但我有一个奇怪的问题,我正在寻找解决方法.
当使用MSVC为模板类型参数(“完全定义的类型”)编译可变参数模板代码时,一切都很好,但是如果我想使用模板模板参数(“部分定义的类型”),则结果变得不正确.
#include <iostream> using namespace std; template <template<typename> class... TS> struct PARTIAL { static void test(std::ostream& out) { out << "PARTIAL-PROBLEM" << endl; } }; template <template<typename> class T> struct PARTIAL<T>{ static void test(std::ostream& out) {out << "PARTIAL-OK-END" << endl;} }; template <template<typename> class T,template<typename> class... TS> struct PARTIAL<T,TS...>{ static void test(std::ostream& out) { out << "PARTIAL-OK" << endl; PARTIAL<TS...>::test(out); } }; template <class... TS> struct FULL { static void test(std::ostream& out) { out << "FULL-PROBLEM" << endl; } }; template <class T> struct FULL<T>{ static void test(std::ostream& out) {out << "FULL-OK-END" << endl;} }; template <class T,class... TS> struct FULL<T,TS...>{ static void test(std::ostream& out) { out << "FULL-OK" << endl; FULL<TS...>::test(out); } }; template <typename T> struct B{}; int main() { FULL<int,int,int>::test(cout); PARTIAL<B,B,B>::test(cout); return 0; }
GCC5.3(MINGW)的输出:
FULL-OK FULL-OK FULL-OK-END PARTIAL-OK PARTIAL-OK PARTIAL-OK-END
MSVC的输出:
FULL-OK FULL-OK FULL-OK-END PARTIAL-OK PARTIAL-OK PARTIAL-OK PARTIAL-PROBLEM
解决方法
向递归案例添加另一个参数将确保不为终止案例选择它:
template <template<typename> class T,template<typename> class T2,template<typename> class... TS> // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ struct PARTIAL<T,T2,TS...>{ // ^^^^ static void test(std::ostream& out) { out << "PARTIAL-OK" << endl; PARTIAL<T2,TS...>::test(out); ^^^^ } };