2016-01-14 2 views
5

Следующая программа дает мне ошибку линковки:Имея constexpr статическую строку дает ошибку Linker

#include <iostream> 

struct Test { static constexpr char text[] = "Text"; }; 

int main() 
{ 
    std::cout << Test::text << std::endl; // error: undefined reference to `Test::text' 
} 

сообщение об ошибке

/tmp/main-35f287.o: In function `main': 
main.cpp:(.text+0x4): undefined reference to `Test::text' 
main.cpp:(.text+0x13): undefined reference to `Test::text' 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

Ok. Давайте попробуем исправить это: добавить определение вне тела struct:

#include <iostream> 

struct Test { static constexpr char text[] = "Text"; }; 
constexpr char Test::text[] = "Text"; 

int main() 
{ 
    std::cout << Test::text << std::endl; 
} 

Clang дает мне следующее сообщение об ошибке.

main.cpp:4:35: error: static data member 'text' already has an initializer 
    constexpr char Test::text[] = "Text"; 
           ^
main.cpp:3:50: note: previous initialization is here 
    struct Test { static constexpr char text[] = "Text"; }; 

О, хорошо, подумал я, теперь я знаю, что вы хотите:

#include <iostream> 

struct Test { static constexpr char text[]; }; 
constexpr char Test::text[] = "Text"; 

int main() 
{ 
    std::cout << Test::text << std::endl; 
} 

И снова об ошибке:

main.cpp:3:41: error: declaration of constexpr static data member 'text' requires an initializer 
    struct Test { static constexpr char text[]; }; 

И собака кусает свой собственный хвост. :(

Есть ли способ использовать постоянные массивы символов времени компиляции, объявленные внутри класса? Причина, по которой я хочу данные внутри класса, заключается в том, что мне нужен класс признаков типов, который помогает мне создавать шаблонные вещи .

+0

Вы имели в виду просто 'struct Test {static const char text [] =" Text "; }; '? –

+1

Вы пробовали два варианта - инициализатор вне класса, как внутри, так и снаружи. Теперь есть третий вариант ... –

+1

Это прекрасно работает: 'struct Test {static constexpr auto text =" Text "; }; ' – vincentp

ответ

8

Должен работать:

#include <iostream> 

struct Test { static constexpr char text[] = "Text"; }; 
constexpr char Test::text[]; 

int main() 
{ 
    std::cout << Test::text << std::endl; 
} 

в стандартной (n4140 §9.4.2/3) вы можете найти:

A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

+0

Только одно назначение инициализации инициализации. –

+0

Работает для меня! Спасибо! –

2

Как сказано в комментарии, эта версия работает отлично:

struct Test { static constexpr auto text = "Text"; }; 

text Но будет const char* вместо char[].

+0

Почему это не работает, чтобы вывести 'const char [5]' из этого? Я имею в виду, почему существует такая разница? Это раздражает. Это делает его непригодным для моих целей. –

 Смежные вопросы

  • Нет связанных вопросов^_^