我有一个将类型与整数值相关联的特征类。

struct traits
{
  private:
    template<int ID> struct type_impl {};
    template<> struct type_impl<1> { using type = int; };
    // ...

  public:
    template<int ID> using type = typename type_impl<ID>::type;

};

我正在编写一个模板函数,它的返回类型由上面的 traits 类提供,并将其专门用于各种 int 值:

  template<int ID> traits::type<ID> function();
  template<> inline traits::type<1> function<1>() { return 42; };
  // ...

这在 VS2015 上编译得很好(参见 https://godbolt.org/z/LpZnni ),但在 VS2017 中却没有,它提示:



令我惊讶的是,声明一个像下面这样的非模板函数会编译:

traits::type<1> other_function();

公开 traits::type_impl 解决了编译问题,但我不明白为什么。对我来说,特化和 other_function 的声明都应该使用 traits::type_impl private 或 none 编译。

感谢您的帮助。

根据@rubenvb 的评论进一步调查
我知道我发布的代码是非法的,所以我尝试进行部分特化(我认为这是合法的):

struct traits
{
  private:
    template<int ID,bool=true> struct type_impl {};
    template<bool B> struct type_impl<1,B> { using type = int; };
    // ...

  public:
    template<int ID> using type = typename type_impl<ID>::type;

};

template<int ID> traits::type<ID> function();
template<> inline traits::type<1> function<1>() { return 42; };

现在每个编译器都很高兴,但 VS2017 仍然希望 traits::type_impl 公开。我想这是一个 Visual Studio 错误。

最佳答案

你有这个代码

struct traits
{
  private:
    template<int ID> struct type_impl {};
    template<> struct type_impl<1> { using type = int; }; // HERE

  public:
    template<int ID> using type = typename type_impl<ID>::type;
};

template<int ID> traits::type<ID> function();
template<> inline traits::type<1> function<1>() { return 42; };

//HERE 标记的行包含类内模板特化。这在 C++ 中是非法的。

我们从中学到的是,当涉及模板时,Visual Studio 会出现可怕的错误消息。如果问题不是很清楚,请查看其他编译器的说明。不同的编译器通常会指向不同的问题或以不同的方式谈论它们,这至少可以很好地暗示实际问题的根源。

英特尔编译器 shows this :
error: explicit specialization is not allowed in the current scope
  template<> struct type_impl<1> { using type = int; };
  ^

海湾合作委员会 shows this :
error: explicit specialization in non-namespace scope 'struct traits'
    5 |     template<> struct type_impl<1> { using type = int; };
      |              ^

Clang doesn't seem to mind 出于某种原因。这似乎是一个错误。

关于c++ - 为什么我的函数模板特化被 VS2017 而不是 VS2015 拒绝?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56021315/

10-11 22:41
查看更多