Search code examples
c++variantstd-function

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?


Solution

  • 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…