【问题标题】:Specialise partial template parameter with type argument (VC++ v140 toolset) [closed]使用类型参数专门化部分模板参数(VC++ v140 工具集)[关闭]
【发布时间】:2017-06-12 10:14:18
【问题描述】:

我尝试构建一个像下面这样的部分模板特化(这在这个简短的形式中没有意义,但它被简化为问题):

#include <iostream>
#include <string>

template<class C> struct A {
    int x;
    std::basic_string<C> y;
};

template <class C, class T>
struct B { B(void) { std::cout << "default "; }; };

template<class C>
struct B<C, decltype(A<C>::x)> { B(void) { std::cout << "int "; }; };

template<class C>
struct B<C, decltype(A<C>::y)> { B(void) { std::cout << "string "; }; };

int main() {
    B<char, int>{};
    B<char, std::string>{};
    B<wchar_t, std::wstring>{};
}

VC++ 编译器(v140 工具集)抱怨部分模板特化说它们是重复的:

错误 C2953:“B”:类模板已定义

我的第一个问题是:上面的代码是否符合标准,即是否应该编译?

如果我将工具集切换到 Visual Studio 2015 - Clang with Microsoft CodeGen (v140_clang_c2),它会编译并运行预期的输出“int string string”,所以我的假设是第一个问题是“是”,因为T 不是非类型。

因此第二个问题是:是否可以改写代码以消除对 C 的依赖,这似乎使 VC++ 崩溃?

还有第三个问题:这是VC++ v140的已知问题吗?

提前致谢, 克里斯托夫

【问题讨论】:

  • 你不是缺少四个class关键字和一个分号吗?
  • 试试this

标签: c++ templates visual-studio-2015


【解决方案1】:

这不是partial class template specialization 的语法。这是:

template <class T, class U>
class Traits { };

template <class T> // one template parameter
class Traits<T, decltype(A<T>::x)> { };
//           ^^^^^^^^^^^^^^^^^^^^

template <class T>
class Traits<T, decltype(A<T>::y)> { };

您还必须使 A::xA::y 可访问。

【讨论】:

    【解决方案2】:

    除了缺少 class 关键字和分号之外,这是一个显式完整类模板特化的示例:

    #include <iostream>
    template<typename T>   // primary template
    struct is_void : std::false_type
    {
    };
    template<>  // explicit specialization for T = void
    struct is_void<void> : std::true_type
    {
    };
    

    【讨论】:

    • 这与问题有什么关系?
    • 完整模板专业化不存在该问题,仅在我必须添加第二个参数时发生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多