简体   繁体   中英

variant of functions with different return types

The code below does not compile:

#include <functional>
#include <variant>

int main() {
  using ret_void = std::function<void()>;
  using ret_int  = std::function<int()>;

  std::variant<ret_void, ret_int> var;
  var.emplace([](){ return 1; } );
}

The compile says template argument deduction/substitution failed . Can anyone explain why this fails to compile?

This fails to compile becausestd::variant::emplace needs to be given either the type or the index of the variant alternative to emplace:

#include <functional>
#include <variant>

int main() {
  using ret_void = std::function<void()>;
  using ret_int  = std::function<int()>;

  std::variant<ret_void, ret_int> var;
  var.emplace<ret_int>([](){ return 1; });
}

The first template parameter of all overloads of std::variant::emplace [variant.mod] is either the index or the type of the variant alternative to emplace. None of these overloads use this parameter in a way that would make it deducible…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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