0

The following code works well on my computer:

#include <string>
#include <variant>
#include <iostream>
int main() {
    std::variant<double, std::string> var;
    var = 20;
    if (std::get_if<0>(&var))
        std::cout << "a double\n";
    else if (std::get_if<1>(&var))
        std::cout << "a string\n";
    return 0;
}

I create a variant containing either a double or a string and then check if the variant holds an element of either type using std::get_if through an index. In constrast, the following code does not compile:

#include <string>
#include <variant>
#include <iostream>
int main() {
    std::variant<double, std::string> var;
    var = 20;
    for (size_t i = 0; i < 2; ++i) {
        if (std::get_if<i>(&var))
            std::cout << i;
    }
    return 0;
}

I am still trying to learn c++, and the documentation is at times still incomprehensible to me.

Can somebody kindly explain how the documentation I linked informs me that I cannot use a size_t (or an int) element to check if the variant holds a particular type?

Second, is there a way to check type membership of a variant in a loop at all?

timrau
  • 22,578
  • 4
  • 51
  • 64
fabian
  • 1,413
  • 1
  • 13
  • 24
  • 2
    The second code doesn't compile because a template argument (even if it's for a template value parameter) must be known at compile time. Constant integers like `0` or `1` are but a variable value is not. Hence, `if (std::get_if(&var))` will not compile because `i` is no valid template argument. – Scheff's Cat May 30 '19 at 12:57
  • 1
    Concerning the last question, this might be of help: [SO: How to make a safer C++ variant visitor, similar to switch statements?](https://stackoverflow.com/a/45708407/7478597) – Scheff's Cat May 30 '19 at 13:01
  • 2
    Already answered here: https://stackoverflow.com/questions/11081573/passing-a-variable-as-a-template-argument – Nikos C. May 30 '19 at 13:06
  • 1
    The TL;DR of this is that a function template is not a function. It's a template for generating functions. Function generation can only happen during compilation and thus any template arguments must be compile-time constants. – Nikos C. May 30 '19 at 13:08
  • 2
    Yet another approach for your code: [**Live Demo on coliru**](http://coliru.stacked-crooked.com/a/77c62594ef27dab8). – Scheff's Cat May 30 '19 at 13:11
  • thank you very much, Scheff and Nikos ! I learned a lot from your comments. – fabian May 30 '19 at 13:18

0 Answers0