【问题标题】:g++ and clang++ different behaviour with variadic containerg++ 和 clang++ 使用可变参数容器的不同行为
【发布时间】:2016-03-26 17:41:09
【问题描述】:

为了练习 C++11,我在玩可变参数模板。

特别是,我正在使用一种递归可变参数容器类 (onion) 和一个返回模板类型数量的函数 (func())。

我遇到了一个案例,clang++ (3.5.0) 无法编译,而 g++ (4.9.2) 编译运行没有问题。

我将其简化如下

#include <iostream>

template <typename F, typename ... O>
struct onion;

template <typename F, typename S, typename ... O>
struct onion<F, S, O...>
 {
   F               first;
   onion<S, O...>  others;
 };

template <typename L>
struct onion<L>
 { L  last; };


template <typename ... Args>
std::size_t func (onion<Args...> const &)
 { return sizeof...(Args); }


int main()
 {
   auto o = onion<int, char const *, float> { 23, { "abcd", {34.0f}} };

   std::cout << func(o) << '\n';

   return 0;
 }

clang++ (3.5.0) 给我以下编译器错误

test.cpp:28:17: error: no matching function for call to 'func'
   std::cout << func(o) << '\n';
                ^~~~
test.cpp:20:13: note: candidate template ignored: substitution
      failure [with Args = <>]: too few template arguments for class template
      'onion'
std::size_t func (onion<Args...> const &)
            ^     ~~~~~
1 error generated.

g++ (4.9.2) 编译没有问题,运行时输出3

我的问题是:谁是对的?

clang++,报错,还是g++,正在编译?

如果我以这种方式重写func(),我补充说

template <typename X, typename ... Args>
std::size_t func (onion<X, Args...> const &)
 { return 1U + sizeof...(Args); }

或者如果我以这种方式重新定义onion

template <typename ... O>
struct onion;

clang++ 和 g++ 编译都没有错误。

【问题讨论】:

  • clang++ 3.7.0 编译它。
  • 你的英语很好。 (在我道歉之前,我没有注意到任何暗示你不是母语人士的东西。)

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


【解决方案1】:

这看起来像是 clang 3.5 中的编译器错误。 如果我用主干版本运行代码,它编译得很好。

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2018-07-21
    • 1970-01-01
    • 2016-06-19
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多