Error c2429 для функция языка структурированные привязки нужен флаг компилятора std c 17

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2429

Compiler Error C2429

11/16/2017

C2429

C2429

57ff6df9-5cf1-49f3-8bd8-4e550dfd65a0

Compiler Error C2429

language feature‘ requires compiler flag ‘compiler option

The language feature requires a specific compiler option for support.

The error C2429: language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ is generated if you try to define a compound namespace, a namespace that contains one or more scope-nested namespace names, starting in Visual Studio 2015 Update 5. (In Visual Studio 2017 version 15.3, the /std:c++latest switch is required.) Compound namespace definitions are not allowed in C++ prior to C++17. The compiler supports compound namespace definitions when the /std:c++17 compiler option is specified:

// C2429a.cpp
namespace a::b { int i; } // C2429 starting in Visual Studio 2015 Update 3.
                          // Use /std:c++17 to fix, or do this:
// namespace a { namespace b { int i; }}

int main() {
   a::b::i = 2;
}

Using MS Visual studio I created a solution containing 2 projects called MainProject and CalcProject
MainProject is a console app that references CalcProject and only contains main() in a .cpp file
CalProject is a library and contains a few header files with the following:

Nml.h contains the following:

#include <cstdint>
#include " Ftr.h"
#include " Mtr.h"

namespace CalcProject::measure

{
    class Mtr;
    class Ftr;

    class Nml
    {
    public:
          ...

Ftr.h contains the following:

#include <cstdint>
#include " Mtr.h"
#include " Nml.h"
namespace CalcProject::measure
{
    class Mtr;
    class Nml;

    class Ftr
    {
        ...

Mtr.h contains the following:

#include " Ftr.h"
#include " Nml.h"
namespace CalcProject::measure
{

   class Ftr;
   class Nml;

    class Mtr
    {
        ...

MainProject.cpp contains the following:

#include "pch.h"
#include "Ftr.h"
#include <iostream>
#include <string>

using namespace CalcProject::measure;

int main()
{

When I build the solution I receive the following error
Error C2429 language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ MainProject
I tried to resolve this by specifying /std:c++17 in the C++ Language standard in the project properties but the error persists.

How can I fix this? Please advise on a possible solution. I am a beginner and this is my first C++ project using multiple header and cpp files to create a library.

Using MS Visual studio I created a solution containing 2 projects called MainProject and CalcProject
MainProject is a console app that references CalcProject and only contains main() in a .cpp file
CalProject is a library and contains a few header files with the following:

Nml.h contains the following:

#include <cstdint>
#include " Ftr.h"
#include " Mtr.h"

namespace CalcProject::measure

{
    class Mtr;
    class Ftr;

    class Nml
    {
    public:
          ...

Ftr.h contains the following:

#include <cstdint>
#include " Mtr.h"
#include " Nml.h"
namespace CalcProject::measure
{
    class Mtr;
    class Nml;

    class Ftr
    {
        ...

Mtr.h contains the following:

#include " Ftr.h"
#include " Nml.h"
namespace CalcProject::measure
{

   class Ftr;
   class Nml;

    class Mtr
    {
        ...

MainProject.cpp contains the following:

#include "pch.h"
#include "Ftr.h"
#include <iostream>
#include <string>

using namespace CalcProject::measure;

int main()
{

When I build the solution I receive the following error
Error C2429 language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ MainProject
I tried to resolve this by specifying /std:c++17 in the C++ Language standard in the project properties but the error persists.

How can I fix this? Please advise on a possible solution. I am a beginner and this is my first C++ project using multiple header and cpp files to create a library.

I aware that someone asked similar question but what I have seen is different error when I try to use c++17 Structure Binding in my code (e.g. for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)), I have already set to use ISO C++17 Standard (/std:c++17) in project properties and checked compiler version.

Ref: Using c++17 ‘structured bindings’ feature in visual studio 2017

Compiler complained
Error C2429 language feature ‘structured bindings’ requires compiler flag ‘/std:c++17’

My Code

TreeNode* ConstructBinaryTree(const int* const intChain, size_t size)
{
    std::list<TreeNode*> nodes;

    for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)
    {
        TreeNode* curr = (it != nodes.end())? *it : nullptr;
        TreeNode* toBeAssiged = new TreeNode(intChain[i]);
        nodes.push_back(toBeAssiged);

        if (curr)
        {
            if (curr->left)
            {
                curr->right = toBeAssiged;
                it++;
            }
            else
            {
                curr->left = toBeAssiged;
            }
        }
    }

    return (nodes.size() == 0)? nullptr : *nodes.begin();
}

According to https://learn.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance?view=vs-2019

Structure binding should be supported after VS 2017 15.3 17

My compiler version
My compiler version

Перейти к контенту

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2429

Compiler Error C2429

11/16/2017

C2429

C2429

57ff6df9-5cf1-49f3-8bd8-4e550dfd65a0

Compiler Error C2429

language feature‘ requires compiler flag ‘compiler option

The language feature requires a specific compiler option for support.

The error C2429: language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ is generated if you try to define a compound namespace, a namespace that contains one or more scope-nested namespace names, starting in Visual Studio 2015 Update 5. (In Visual Studio 2017 version 15.3, the /std:c++latest switch is required.) Compound namespace definitions are not allowed in C++ prior to C++17. The compiler supports compound namespace definitions when the /std:c++17 compiler option is specified:

// C2429a.cpp
namespace a::b { int i; } // C2429 starting in Visual Studio 2015 Update 3.
                          // Use /std:c++17 to fix, or do this:
// namespace a { namespace b { int i; }}

int main() {
   a::b::i = 2;
}

Using MS Visual studio I created a solution containing 2 projects called MainProject and CalcProject
MainProject is a console app that references CalcProject and only contains main() in a .cpp file
CalProject is a library and contains a few header files with the following:

Nml.h contains the following:

#include <cstdint>
#include " Ftr.h"
#include " Mtr.h"

namespace CalcProject::measure

{
    class Mtr;
    class Ftr;

    class Nml
    {
    public:
          ...

Ftr.h contains the following:

#include <cstdint>
#include " Mtr.h"
#include " Nml.h"
namespace CalcProject::measure
{
    class Mtr;
    class Nml;

    class Ftr
    {
        ...

Mtr.h contains the following:

#include " Ftr.h"
#include " Nml.h"
namespace CalcProject::measure
{

   class Ftr;
   class Nml;

    class Mtr
    {
        ...

MainProject.cpp contains the following:

#include "pch.h"
#include "Ftr.h"
#include <iostream>
#include <string>

using namespace CalcProject::measure;

int main()
{

When I build the solution I receive the following error
Error C2429 language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ MainProject
I tried to resolve this by specifying /std:c++17 in the C++ Language standard in the project properties but the error persists.

How can I fix this? Please advise on a possible solution. I am a beginner and this is my first C++ project using multiple header and cpp files to create a library.

Using MS Visual studio I created a solution containing 2 projects called MainProject and CalcProject
MainProject is a console app that references CalcProject and only contains main() in a .cpp file
CalProject is a library and contains a few header files with the following:

Nml.h contains the following:

#include <cstdint>
#include " Ftr.h"
#include " Mtr.h"

namespace CalcProject::measure

{
    class Mtr;
    class Ftr;

    class Nml
    {
    public:
          ...

Ftr.h contains the following:

#include <cstdint>
#include " Mtr.h"
#include " Nml.h"
namespace CalcProject::measure
{
    class Mtr;
    class Nml;

    class Ftr
    {
        ...

Mtr.h contains the following:

#include " Ftr.h"
#include " Nml.h"
namespace CalcProject::measure
{

   class Ftr;
   class Nml;

    class Mtr
    {
        ...

MainProject.cpp contains the following:

#include "pch.h"
#include "Ftr.h"
#include <iostream>
#include <string>

using namespace CalcProject::measure;

int main()
{

When I build the solution I receive the following error
Error C2429 language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:c++17’ MainProject
I tried to resolve this by specifying /std:c++17 in the C++ Language standard in the project properties but the error persists.

How can I fix this? Please advise on a possible solution. I am a beginner and this is my first C++ project using multiple header and cpp files to create a library.

I aware that someone asked similar question but what I have seen is different error when I try to use c++17 Structure Binding in my code (e.g. for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)), I have already set to use ISO C++17 Standard (/std:c++17) in project properties and checked compiler version.

Ref: Using c++17 ‘structured bindings’ feature in visual studio 2017

Compiler complained
Error C2429 language feature ‘structured bindings’ requires compiler flag ‘/std:c++17’

My Code

TreeNode* ConstructBinaryTree(const int* const intChain, size_t size)
{
    std::list<TreeNode*> nodes;

    for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)
    {
        TreeNode* curr = (it != nodes.end())? *it : nullptr;
        TreeNode* toBeAssiged = new TreeNode(intChain[i]);
        nodes.push_back(toBeAssiged);

        if (curr)
        {
            if (curr->left)
            {
                curr->right = toBeAssiged;
                it++;
            }
            else
            {
                curr->left = toBeAssiged;
            }
        }
    }

    return (nodes.size() == 0)? nullptr : *nodes.begin();
}

According to https://learn.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance?view=vs-2019

Structure binding should be supported after VS 2017 15.3 17

My compiler version
My compiler version

I aware that someone asked similar question but what I have seen is different error when I try to use c++17 Structure Binding in my code (e.g. for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)), I have already set to use ISO C++17 Standard (/std:c++17) in project properties and checked compiler version.

Ref: Using c++17 ‘structured bindings’ feature in visual studio 2017

Compiler complained
Error C2429 language feature ‘structured bindings’ requires compiler flag ‘/std:c++17’

My Code

TreeNode* ConstructBinaryTree(const int* const intChain, size_t size)
{
    std::list<TreeNode*> nodes;

    for (auto [i, it] = std::tuple{ 0, nodes.begin() }; i < size; i++)
    {
        TreeNode* curr = (it != nodes.end())? *it : nullptr;
        TreeNode* toBeAssiged = new TreeNode(intChain[i]);
        nodes.push_back(toBeAssiged);

        if (curr)
        {
            if (curr->left)
            {
                curr->right = toBeAssiged;
                it++;
            }
            else
            {
                curr->left = toBeAssiged;
            }
        }
    }

    return (nodes.size() == 0)? nullptr : *nodes.begin();
}

According to https://learn.microsoft.com/en-us/cpp/overview/visual-cpp-language-conformance?view=vs-2019

Structure binding should be supported after VS 2017 15.3 17

My compiler version
My compiler version

MJ_PRUTYG

3 / 3 / 0

Регистрация: 28.11.2018

Сообщений: 242

1

18.01.2021, 22:40. Показов 2475. Ответов 6

Метки нет (Все метки)


Проблема с вложенными namespace-ами: C2429: language feature ‘nested-namespace-definition’ requires compiler flag ‘/std:
Как решить эту проблема? Потому что вся моя библиотека, которая написана с этими вложенными namespace-ами, должна работать и в Qt — но переписывать все неймспейсы на НЕ вложенные — очень геморная и костыльная(что главное) работа.

Как это решить?

Ругается на этот код:

C++
1
2
3
4
5
6
#pragma once
namespace vk::unsafe {//language feature 'nested-namespace-definition' requires compiler flag '/std:c++17'
 
class DB{
};
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Алексей1153

фрилансер

4478 / 3988 / 870

Регистрация: 11.10.2019

Сообщений: 10,503

19.01.2021, 07:32

2

MJ_PRUTYG,

C++
1
2
3
4
5
6
7
8
9
10
#pragma once
namespace vk
{
   namespace unsafe
   {
      class DB
      {
      };
   }
}

Добавлено через 54 секунды
ну или дать компилятору флаг, который он там хочет — /std:c++17

Добавлено через 3 минуты
в pro-файле добавь строку
CONFIG+=c++17



1



MJ_PRUTYG

3 / 3 / 0

Регистрация: 28.11.2018

Сообщений: 242

19.01.2021, 10:56

 [ТС]

3

Алексей1153, уже всё это сделал, добавил в конфиг CONFIG+=c++17 — но не работает

Добавлено через 2 минуты

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

C++
1
2
3
4
5
6
7
8
9
10
#pragma once
namespace vk
{
   namespace unsafe
   {
      class DB
      {
      };
   }
}

я понимаю, что так можно записать. Но это столько кода переписывать…. ужас.

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

ну или дать компилятору флаг, который он там хочет — /std:c++17

Кстати, я же так понимаю, что CONFIG+=c++17 и /std:c++17 — это один и тот же параметр. Только через конфиг это в среде Qt а /std:c++17 это напрямую команда компилятору. Я верно понимаю?



0



фрилансер

4478 / 3988 / 870

Регистрация: 11.10.2019

Сообщений: 10,503

19.01.2021, 11:10

4

MJ_PRUTYG, а IDE какая ?

Добавлено через 3 минуты
если студия, то
свойства проекта — general — C++ language standart



1



MJ_PRUTYG

3 / 3 / 0

Регистрация: 28.11.2018

Сообщений: 242

19.01.2021, 11:21

 [ТС]

5

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

а IDE какая ?

В студии я-то вот тоже знаю. 3 года(весь мой опыт) работал на студии. Теперь перешел на Qt. Очень непривычно.
А в Qt ставлю флаг

C++ (Qt)
1
CONFIG += c++17

а оно вообще не включает семнадцатые плюсы О_о. Т.к. даже определение шаблона по аргументам(не помню как правильно называется) — не работает. В общем, все плюшки, которые в 17х плюсах — не работают. Хотя в конфиге я прописал вроде подключение.

Добавлено через 1 минуту
Пробовал уже и

C++ (Qt)
1
2
3
CONFIG += c++17
CONFIG += c++latest
CONFIG += /std:c++17 - вообще не распознает(ну оно и понятно)



0



Алексей1153

фрилансер

4478 / 3988 / 870

Регистрация: 11.10.2019

Сообщений: 10,503

19.01.2021, 16:50

6

Цитата
Сообщение от MJ_PRUTYG
Посмотреть сообщение

Теперь перешел на Qt.

таки QtCreator? А компилятор какой? У меня mingw32, например. Всё вроде работает

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace ns1
{
    namespace ns2
    {
        class c1
        {
            void f1();
        };
 
        class c2;
    };
};
 
namespace ns1::ns2
{
    void c1::f1()
    {
    }
 
    class c2
    {
    };
};



1



3 / 3 / 0

Регистрация: 28.11.2018

Сообщений: 242

20.01.2021, 13:37

 [ТС]

7

Цитата
Сообщение от Алексей1153
Посмотреть сообщение

А компилятор какой?

Компилятор MCVS 16.x — вроде всё должно работать, поддерживает КАК НАПИСАНО 17е Плюсы.

В общем, проблему решил. Решил тем, что просто установил и «приловчился» работать с Qt на VS. Спасибо за помощь.



0



#include <iostream>
#include <iomanip>
#include <memory>

using namespace std;

struct Foo {
    int value;

    Foo(int i) : value{i} {}
    ~Foo() { cout << "DTOR Foo " << value << 'n'; }
};

void weak_ptr_info(const weak_ptr<Foo> &p)
{
    cout << "---------" << boolalpha
         << "nexpired:   " << p.expired()
         << "nuse_count: " << p.use_count()
         << "ncontent:   ";

    // c ++ 17 новых функций
    if (const auto sp (p.lock()); sp) {
        cout << sp->value << 'n';
    } else {
        cout << "<null>n";
    }
}


int main()
{
    weak_ptr<Foo> weak_foo;

    weak_ptr_info(weak_foo);

    {
        auto shared_foo (make_shared<Foo>(1337));
        weak_foo = shared_foo;

        weak_ptr_info(weak_foo);
    }

    weak_ptr_info(weak_foo);
}

При использовании vs2017 появится следующая ошибка, решение будет следующим:

Свойства проекта — все параметры c / c ++ — стандарт языка c ++ стандарт iso c ++ 17 (/ std: c ++ 17)

1> f: code_pro weakptr weakptr weakptr.cpp (27): ошибка C2429: языковой функции «инструкция-инициала в if / switch» требуется флаг компилятора «/ std: c ++ 17»

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error c2338 windows headers require the default packing option
  • Error c231 redefinition
  • Error c2259 невозможно создать экземпляр абстрактного класса
  • Error c2248 cannot access private member declared in class
  • Error c2238 непредвиденные лексемы перед

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии