我有一些C++ 11模板代码我试图移植到Visual C++编译器2015.原始代码工作得很好,但是我需要重写它以解决问题与constexpr。为什么静态const char *模板struct成员未初始化
The original code (simplified example)
#include <iostream>
struct String
{
static constexpr const char * value{ "STRING" };
};
template<typename Base>
class Derived
{
public:
static constexpr const char * value{ Base::value };
};
template<typename BarType>
struct Foo
{
static constexpr const char * value{ BarType::value };
};
using Bar = Derived<String>;
using FooBar = Foo<Bar>;
int main()
{
std::cout << "FooBar::value = " << FooBar::value << std::endl;
}
此打印:
FooBar::value = STRING
然而,当我重写,一些静态变量不被初始化。即使它编译得很好。
#include <iostream>
struct String
{
static const char * value;
};
const char * String::value = "STRING";
template<typename Base>
class Derived
{
public:
static const char * value;
};
template<typename Base>
const char * Derived<Base>::value = { Base::value };
template<typename BarType>
struct Foo
{
static const char * value;
};
template<typename BarType>
const char * Foo<BarType>::value = { BarType::value };
using Bar = Derived<String>;
using FooBar = Foo<Bar>;
int main()
{
std::cout << "FooBar::value = " << FooBar::value << std::endl;
}
此打印:
// nothing (Segmentation fault)
这究竟是为什么?
我该如何解决/解决它?
这可以在Clang和Visual-C++中重现,但在第二个例子中GCC也会打印FooBar::value = STRING
。
至于建议由@哔叽,贝勒斯特。我喜欢这个解决方案,因为它与原始代码非常相似。当constexpr成员添加到VS时易于应用和轻松删除。
为什么_what_发生?是[输出'STRING'](http://coliru.stacked-crooked.com/a/21f5265df51c0047)不是你所期望的? –
有人编辑了非工作代码的链接。生病了。 STRING预计。 – Mathias
用'template class Derived明确实例化这两个类; template struct Foo >;'使用前[解决段错误](http://melpon.org/wandbox/permlink/fkZHNjXNrMA1gAO8) –