在template中使用std::variant的template函数
Use of emplace function of std::variant in template
我正在试验最终状态机和std::variant<gt;
std::variant将包含所有可能的状态。状态将在State类中定义。
我希望std::monostate作为第一种State变体,将其用作";"不改变状态";价值所以定义是:第一种类型是std::monstate,第二种类型是fsm的初始状态。
由于std::变量被初始化为它的第一个元素,我想使用template<1>在构造函数中。
template <typename StateVariant>
class fsm
{
public:
StateVariant state;
fsm()
{
state.emplace<1>();
};
};
struct Initial{};
struct Running{};
using State = std::variant<std::monostate,Initial,Running>;
fsm<State> myFSM;
但这给出了compiletime错误:
..fsm_emplace.cpp: In constructor 'fsm<StateVariant>::fsm()':
..fsm_emplace.cpp:15:20: error: expected primary-expression before ')' token
15 | state.emplace<1>();};
然而,当我在非模板代码中使用相同的构造时:
State myState;
void setup()
{
myState.emplace<1>();
}
模板函数的使用是否有限制?
由于state
依赖于模板名称,因此必须添加template
:
state.template emplace<1>();
模板函数的使用有限制吗?
我不知道正式规则的措辞,但你需要在这里使用template
关键字。clang给出了一个更具描述性的错误";依赖模板名称"template"之前缺少"template"关键字";。将state.emplace<1>();
更改为state.template emplace<1>();
将修复构建错误。
尽管就其价值而言,我也认为在成员初始值设定项中使用in_place_index_t
(由Nicol Bolas在评论中建议(是一个更优雅的解决方案。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 传递给std::function template的template参数究竟代表什么
- 在template中使用std::variant的template函数
- C++中原子的替代品<variant>
- boost::spirit::karma 替代生成器,带有 boost::variant 由字符串和字符串别名组成
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- 为 std::variant 提供一个运算符 ==
- 如何使用 std::variant 打印地图键/值?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- C++ template for QList
- C++ - 为什么这里需要'template'关键字?
- 在 std::tuple 上使用 std::variant 的问题
- 如何访问存储在 std::variant 中的类的方法
- 使用"std::enable_if_t" "function template has already been defined"
- 更改其类型后,丢失对 std::variant 对象的引用
- 调用方如何知道 VARIANT 中何时有十进制?
- std::visit and std::variant usage
- C++模板错误:"invalid explicitly-specified argument for template parameter"
- std::variant vs指向C++中异构容器基类的指针
- min and max Variadic Template variant in C++11?