Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
Tes Avatar asked Jan 26 '23 12:01

Tes


1 Answers

This fails to compile because std::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…

like image 178
Michael Kenzel Avatar answered Jan 28 '23 01:01

Michael Kenzel