【发布时间】:2015-10-10 10:45:00
【问题描述】:
这是我的工作代码示例:
#include <iostream>
template<typename B>
class b {
public:
int y;
constexpr b(int x) : y(x) {
}
constexpr void sayhi() {
std::cout << "hi" << std::endl;
}
};
template<int x>
struct A {
static constexpr b<int> bee = x;
static constexpr int y = x; // this one is fine and usable already, I don't have to do something like what I did on member bee
inline static void sayhi() {
std::cout << y << std::endl;
}
};
template<int x>
constexpr b<int> A<x>::bee; // why do I have to do something like this, it will cause errors if I don't.
int main(int argc, char** argv) {
A<30>::bee.sayhi(); // works fine
A<30>::sayhi(); // works fine
return 0;
}
我的代码做的很简单,我有模板结构A,它有两个静态变量,即static constexpr int y 和static constexpr b<int> bee = x;。我的模板结构A 将获取参数的值,该参数将由x 从模板参数中复制。我的问题是:当涉及到类时,我必须通过执行以下操作来初始化类:
template<int x>
constexpr b<int> A<x>::bee;
如果我不使用上面的代码,我会收到 undefined 引用错误。其中 int 已经很好并且只需执行以下操作即可访问:
static constexpr int y = x;
我担心为什么我不必再转发声明了。
【问题讨论】: