user14839139
user14839139

Reputation:

std::variant declaration is not found by compiler

What I am trying to do is very simple, I need to create a vector that can hold different types of data. So I read about std::variant and am trying to use it, however, when declaring my "std::vector< std::variant< typenames > >", the compiler complains about not finding the declaration for variant<> even though I included the variant library. (errors are "use of undeclared identifier variant" with implicit namespace, and "no member named 'variant' in namespace 'std'" with explicit namespace). My Clang version is 11, and I am using c++17, so I don't know what I could be missing here. For what it's worth, I am currently using VScode 1.53. This is my c_cpp_properties.json :

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/clang",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-clang-x64"
        }
    ],
    "version": 4
}

I have tried also changing the cpp version in the default GUI provided by vscode to manage the cpp compiler, that made no difference.

What I am doing is something similar to this:

#include <vector>
#include <variant>

struct c {
    std::vector< std::variant<glm::vec2, glm::vec3, glm::vec4>> v;
};

Does anyone have any idea why this is happening, or had this problem before and knows a solution?

Solution: Turns out specifying the cpp standard on the file c_cpp_properties.json is not enough. You have to add "-std=c++17" to tasks.json as well, after "-g", like this:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-g",
                "-std=c++17",
                     ...

Upvotes: 1

Views: 3671

Answers (2)

SimonFarron
SimonFarron

Reputation: 362

I am not a Clang expert, but try using the option -std=c++17.

According to this the default seems to be C++98.

Upvotes: 2

Skewjo
Skewjo

Reputation: 399

This appears to work fine in MSVC:

#include <variant>

struct c {
    std::vector< std::variant<int, float>> v;
}

It seems like the compiler might be throwing a fit about the template type nesting(wild guess here). Maybe try the following as a workaround:

#include <variant>

struct c {
    typedef std::variant< int, float> TwoPartVariant;
    std::vector< TwoPartVariant> v;
};

Upvotes: 0

Related Questions