gpt4 book ai didi

c++ - Variadic 模板和 "expected a type"错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:30 26 4
gpt4 key购买 nike

我正在(主要是出于学习目的)自己实现 tuple,我刚刚遇到了一个问题。我有以下代码:

namespace Rose
{
template<typename T>
struct RemoveReference
{
typedef T Type;
};

template<typename T>
struct RemoveReference<T &>
{
typedef T Type;
};

template<typename... Elems>
class Tuple;

template<typename First, typename... Elems>
class Tuple<First, Elems...>
{
public:
Tuple(First a, Elems... more)
: More(more...), Element(a)
{
}

Tuple<First, Elems...> & operator=(const Tuple<RemoveReference<First>::Type,
RemoveReference<Elems>::Type...> & rhs)
{
this->Element = rhs.Element;
this->More = rhs.More;

return *this;
}

private:
Tuple<Elems...> More;
First Element;
};

template<typename Only>
class Tuple<Only>
{
public:
Tuple(Only a) : Element(a)
{
}

Tuple<Only> & operator=(const Tuple<RemoveReference<Only>::Type> & rhs)
{
this->Element = rhs.Element;

return *this;
}

private:
Only Element;
};
}

int main()
{
Rose::Tuple<int, float, int> t(1, 1.f, 2);
}

导致如下错误(错误较多,但这个是必不可少的):

error: type/value mismatch at argument 1 in template parameter list for 'template struct Rose::Tuple' error: expected a type, got 'Rose::RemoveReference::Type'

我不太明白这是怎么回事。 RemoveReference 特性在单独使用时有效。

这里有两个测试用例:

我已经用 G++ 4.6.1、4.5.1 和 Clang++ 2.9 试过这段代码。

出现这些错误的原因是什么?

最佳答案

RemoveReference<T>::Type是依赖类型,所以需要加上typename这里:

        Tuple<First, Elems...> & operator=(const Tuple<typename RemoveReference<First>::Type,
typename RemoveReference<Elems>::Type...> & rhs)

可能还有其他地方。

关于c++ - Variadic 模板和 "expected a type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10357471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com