我有一些 C++11 模板代码,我正在尝试移植到 Visual C++ Compiler 2015。原始代码工作得很好,但是我需要重写它以解决 constexpr 的问题。
#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++ 中重现,但是 GCCFooBar::value = STRING
也会在第二个示例中打印。
更新:工作解决方案
正如@serge-ballesta 所建议的那样。我更喜欢这个解决方案,因为它与原始代码非常相似。当 constexpr 成员添加到 VS 时,可以轻松应用和轻松删除。