Kyl*_*and 5 c++ variadic-templates c++11
我正在思考可能的实现std::tuple(和任何类似的模板类,在编译时定义了可变数量的"成员"),我想也许可以创建一个类似于链表的"递归类型".我尝试编译以下测试用例:
template <typename FirstType, typename... OtherTypes>
class TupleLite
{
public:
FirstType type_;
TupleLite<OtherTypes...> other_types_;
};
int main()
{
TupleLite<int,double> mytuple;
}
Run Code Online (Sandbox Code Playgroud)
类本身编译时没有错误,但实例化会抛出错误wrong number of template arguments (0, should be 1 or more).我相信这是因为TupleLite<int, double>尝试实例化a TupleLite<double>,它试图实例化a TupleLite<>,没有有效的定义.
这个"递归大小的班级"可以被抢救吗?我尝试定义如下的"无争论专业化" TupleLite:
template <>
class TupleLite {}
Run Code Online (Sandbox Code Playgroud)
....但这似乎不起作用,虽然g++并且clang++似乎在确切原因上存在分歧.
从中g++,最相关的错误似乎是:
error: template specifiers not specified in declaration of ‘template<class FirstType, class ... OtherTypes> class TupleLite’
class TupleLite
^
error: wrong number of template arguments (0, should be 1 or more)
TupleLite<OtherTypes...> other_types_;
^
Run Code Online (Sandbox Code Playgroud)
clang++但是,他说:
error: extraneous 'template<>' in declaration of class 'TupleLite'
template <>
^
error: redefinition of 'TupleLite' as different kind of symbol
class TupleLite
^
Run Code Online (Sandbox Code Playgroud)
的主要模板定义TupleLite指定它至少需要一个模板参数FirstType。由于这不是您想要表达的内容,因此请提供一个主要模板定义,该定义最终也会处理空情况,如下所示:
template <typename...>
class TupleLite{};
Run Code Online (Sandbox Code Playgroud)
以及一个部分专业化:
template <typename FirstType, typename... OtherTypes>
class TupleLite<FirstType, OtherTypes...>
{
public:
FirstType type_;
TupleLite<OtherTypes...> other_types_;
};
Run Code Online (Sandbox Code Playgroud)
编辑:感谢 Nikos 指出在这种情况下不需要空规范。
| 归档时间: |
|
| 查看次数: |
547 次 |
| 最近记录: |