为了练习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 ++编译都没有错误。
答案 0 :(得分:1)
这看起来像是clang 3.5中的编译器错误。 如果我使用trunk版本运行代码,它可以很好地编译。