【问题标题】:clang++ auto return type error for specialization of templated method in templated class?模板类中模板方法专业化的clang自动返回类型错误?
【发布时间】:2016-10-29 22:36:17
【问题描述】:

为了理解another question,我已经简化了示例,得到以下代码。

template <bool>
struct foo
 {
   template <typename T>
      auto bar (int i)
       { return i; }
 };

template <>
template <typename T>
   auto foo<true>::bar (int i)
    { return i; }

int main()
 {
   return 0;
 }

g++ 4.9.2 编译没有问题; clang++ 3.5 报如下错误

tmp_003-14,gcc,clang.cpp:12:20: error: out-of-line definition of 'bar' does not
      match any declaration in 'foo<true>'
   auto foo<true>::bar (int i)
                   ^~~

int 替换两个auto 返回值之一,没有变化:g++ compile 和clang++ 给出错误。将auto 替换为int,错误消失。

template &lt;typename T&gt; 部分很重要,因为以下代码在两个编译器上都没有问题

template <bool>
struct foo
 {
      auto bar (int i)
       { return i; }
 };

template <>
   auto foo<true>::bar (int i)
    { return i; }

int main()
 {
   return 0;
 }

我的问题很明显:谁是对的?

g++ 还是 clang++?

我认为 g++ 是正确的,这是来自 clang++ 的错误,但我要求确认。

ps:对不起,我的英语不好。

【问题讨论】:

  • 试试 gcc 6.1 和 clang 3.8 ..
  • 这是一个 Clang 问题。它适用于 3.8:godbolt.org/g/JkCJ6l

标签: c++ templates c++14 clang++ auto


【解决方案1】:

我遇到了同样的问题,这里是solution。 除了您还应该考虑到仅从 C++14 起才允许隐式自动返回类型,因此您应该使用 -std=c++14 编译标志,或显式设置返回类型(对于 C++11)。

问题是 CLang 不能很好地匹配模板类的模板函数的特化。为了克服这个问题,你应该有一个空的模板类声明和单独的特化:

template <bool>
struct foo;

template <>
struct foo <false>
{
   template <typename T>
   auto bar (int i)
   { return i; }
};


template <>
struct foo <true>
{
   template <typename T>
   auto bar (int i)
   { return i; }
};

int main()
{
   return 0;
}

【讨论】:

  • 感谢您的努力,但您指向“解决方案”的链接与我在问题中引用的“另一个问题”的链接相同。公认的“解决方案”是我对这个问题的回答。而且,显然,在哪里谈论 C++14,非 C++11,如何标记(没有 C++11 标记)。我的问题不是“如何解决?”但是“谁是对的?”。你是说(如果我理解正确的话)“g++ 是对的,而 clang++ 是错的”。但我希望在答案中引用官方标准的相关部分。 (再次抱歉我的英语不好)。
  • 嗨@max66,很抱歉我没有立刻认出你,你是第一个提供解决方案的人。对我来说,“谁是对的”毫无疑问:标准允许模板声明也是定义,它允许模板专业化。因此,很明显,在模板类声明也是它的定义的情况下,CLang 只是缺少对模板类进行专门化的模板函数定义。这不是 CLand 错误,只是尚未实现功能,因为 CLang 还很年轻,而且 CLang 3.8.1 与 GCC 4.2.1(这是一个相当旧的版本)兼容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多