C-строка как шаблонный параметр нетипичного типа работает в gcc 6.3, но не работает в Visual Studio 2017 (19.16.27027.1 для x64) - PullRequest
6 голосов
/ 02 апреля 2019

Следующий код:

#include <iostream>

template<const char* Pattern> void f() {
    std::cout << Pattern << "\n";
}

static constexpr const char hello[] = "Hello";

int main() {
    f<hello>(); //Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
    //  Copyright (C) Microsoft Corporation.  All rights reserved.
    //
    //  string-as-template-parameter.cpp
    //  string-as-template-parameter.cpp(10): fatal error C1001: An internal error has occurred in the compiler.
    //  (compiler file 'msc1.cpp', line 1518)
    //   To work around this problem, try simplifying or changing the program near the locations listed above.
    //  Please choose the Technical Support command on the Visual C++
    return 0;
}

работает при компиляции gcc (g ++ (Debian 6.3.0-18 + deb9u1) 6.3.0 20170516), но приводит к C1001 при компиляции VS 2017.

В качестве обходного пути я использую:

#include <iostream>

template<const char** Pattern> void f() {
    std::cout << *Pattern << "\n";
}

static const char* hello = "Hello";

int main() {
    f<&hello>();
    return 0;
}

Кто-нибудь имеет представление о более красивом решении?Может быть, в исходном коде есть ошибка, которая пропускается gcc?

1 Ответ

5 голосов
/ 02 апреля 2019

Кто-нибудь имеет представление о более красивом решении?

Вместо этого можно использовать ссылку на std::string.

#include <iostream>
#include <string>

template<std::string & Pattern> void f() {
    std::cout << Pattern << "\n";
}

static std::string hello = "Hello";

int main() {
    f<hello>(); 
    return 0;
}

Это компилируется с MSVC в Visual Studio .

Этоработает, потому что согласно Cppreference , именованная ссылка lvalue со связью разрешена в качестве нетипового параметра.(Обратите внимание, что hello не является локальным.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...