MSVC2015更新3可变参数模板解决方法

时间:2016-06-21 15:13:05

标签: c++ c++11 visual-c++ variadic-templates

Visual Studio 2015更新3改进了对C ++ 11的支持,但我有一个奇怪的问题,我正在寻找解决方法。

使用MSVC为模板类型参数编译可变参数模板代码("完全定义的类型")一切都很好,但是如果我想使用模板模板参数("部分定义的类型&#34) ;),结果变得不正确。

#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

MSVC为完全定义的类型和部分生成代码的不同方式。什么应该是最好的解决方法?

here is demo that works good on GCC

1 个答案:

答案 0 :(得分:4)

在递归案例中添加另一个参数将确保不为终止案例选择它:

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);
                ^^^^
    }
};