4

Example code:

#include <variant>

template<typename T>
std::variant<int, T> f(bool select, int v1, T v2)
{
    std::variant<int, T> v;
    if (select == false)
        v.emplace<int>(v1);
    else
        v.emplace<T>(v2);
    return v;
}

int main()
{
    auto v = f<float>(true, 1, 2.0f);
}

Trying to compile it gives following error:

$ g++ -std=gnu++17 variant.cpp 
variant.cpp: In function ‘std::variant<int, T> f(bool, int, T)’:
variant.cpp:8:13: error: expected primary-expression before ‘int’
   v.emplace<int>(v1);
             ^~~
variant.cpp:8:13: error: expected ‘;’ before ‘int’
   v.emplace<int>(v1);
             ^~~
             ;
variant.cpp:10:14: error: expected primary-expression before ‘>’ token
   v.emplace<T>(v2);
              ^

How can I fix this usage scenario, where I need to use std::variant inside a function template (actually a member function of a class template, but the problem is the same)? Changing types to indexes (emplace<int> -> emplace<0>, emplace<T> -> emplace<1>) doesn't help, as then GCC seems to think that I want to compare function with integer:

$ g++ -std=gnu++17 variant.cpp 
variant.cpp: In instantiation of ‘std::variant<int, T> f(bool, int, T) [with T = float]’:
variant.cpp:16:33:   required from here
variant.cpp:8:12: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
   v.emplace<0>(v1);
   ~~~~~~~~~^~
variant.cpp:10:12: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
   v.emplace<1>(v2);
   ~~~~~~~~~^~

Is this a bug or a feature?

Freddie Chopin
  • 8,440
  • 2
  • 28
  • 58

0 Answers0