简体   繁体   English

需要从枚举(类)到 std::binary_function 的 map

[英]Need a map from enum (class) to std::binary_function

I have this enum (class)我有这个枚举(类)

enum class conditional_operator
{
    plus_op,
    or_op,
    not_op
}

And I'd like a std::map that represents these mappings:我想要一个代表这些映射的std::map

std::map<conditional_operator, std::binary_function<bool,bool,bool>> conditional_map = 
        { { conditional_operator::plus_op, std::logical_and<bool> },
          { conditional_operator::or_op,   std::logical_or<bool>},
          { conditional_operator::not_op,  std::binary_negate<bool>} // this seems fishy too, binary_negate is not really what I want :(

Apart from the fact that this doesn't compile:除了这不能编译的事实之外:

error: expected primary-expression before '}' token错误:“}”标记之前的预期主表达式

error: expected primary-expression before '}' token错误:“}”标记之前的预期主表达式

error: expected primary-expression before '}' token错误:“}”标记之前的预期主表达式

for each of the three lines, how should I do this?对于三行中的每一行,我应该怎么做? I think a logical_not with a second dummy argument would work, once I get this to compile of course...我认为带有第二个虚拟参数的logical_not会起作用,当然,一旦我得到它来编译......

EDIT: Could I use lambda's for this?编辑:我可以为此使用 lambda 吗?

You really want std::function<bool(bool, bool)> , not std::binary_function<bool, bool, bool> .你真的想要std::function<bool(bool, bool)> ,而不是std::binary_function<bool, bool, bool> That only exists for typedefs and stuff in C++03.这只存在于 C++03 中的 typedef 和东西。 Secondly, I'd just use a lambda- they're short enough and much clearer.其次,我只使用 lambda - 它们足够短且更清晰。 The std::logical_and and stuff only exists for C++03 function object creation, and I'd use a lambda over them any day. std::logical_and和东西只存在于 C++03 function object 创建,我会在任何一天使用 lambda 。

std::map<conditional_operator, std::function<bool(bool,bool)>> conditional_map = 
{ 
    { conditional_operator::plus_op, [](bool a, bool b) { return a && b; } },
    { conditional_operator::or_op,   [](bool a, bool b) { return a || b; } },
    { conditional_operator::not_op,  [](bool a, bool b) { return !a; } }
};

Wait- what exact operator are you referring to with not?等等 - 你指的是哪个确切的运营商? Because that's unary, as far as I know.因为这是一元的,据我所知。

@DeadMG's answer is spot-on but if you insist on using the predefined function objects, you need to instantiate them. @DeadMG 的答案很明确,但如果您坚持使用预定义的 function 对象,则需要实例化它们。 At the moment you're just passing their type names.目前你只是传递他们的类型名称。

That is, you need to write std::logical_***<bool>() instead of just std::logical_***<bool> .也就是说,您需要编写std::logical_***<bool>()而不仅仅是std::logical_***<bool>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM