Следующая программа дает мне ошибку линковки:Имея 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[]; };
И собака кусает свой собственный хвост. :(
Есть ли способ использовать постоянные массивы символов времени компиляции, объявленные внутри класса? Причина, по которой я хочу данные внутри класса, заключается в том, что мне нужен класс признаков типов, который помогает мне создавать шаблонные вещи .
Вы имели в виду просто 'struct Test {static const char text [] =" Text "; }; '? –
Вы пробовали два варианта - инициализатор вне класса, как внутри, так и снаружи. Теперь есть третий вариант ... –
Это прекрасно работает: 'struct Test {static constexpr auto text =" Text "; }; ' – vincentp