Boost.Variant, Boost.MPL: How to append types?

流过昼夜 提交于 2019-12-02 11:28:38

It is not possible. operator[] is a run-time thing, while types are a compile-time thing. So should the compiler compile the following?

char const* str;
if (some_condition())
  str = "voidFunc";
else
  str = "stringFunc";
// ... some more code
if (some_condition())
  funcs[str]();
else
  funcs[str](str);

How is the compiler supposed to know whether the second call to some_condition() gives the same result as before? Or whether the code in between modified the value of str?

What about the following:

void call(some_map_like_type<std::string, boost::variant> const& funcs)
{
  funcs["voidFunc"]();
}

How is the compiler supposed to know whether at call time funcs contains an entry mapping "voidFunc"to a function with no arguments? And what should happen if it is called once on with a value that does, and once with a value which doesn't?

Depending on what you actually want to achieve, there might be a way to get it with templates and constexpr functions. However note that nothing which happens at runtime can affect whether the code compiles, for the simple reason that the code cannot be run before it is compiled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!