【发布时间】:2016-01-25 02:15:21
【问题描述】:
我遇到了模板结构的静态 constexpr 成员的一些问题。代码编译但我得到链接错误。这是我正在尝试做的事情:
template<int n>
struct Test {
static constexpr auto invoke = make_tuple(2, "test", 3.4);
};
template<typename T>
void test(T&& t) {
cout << t << endl;
}
int main() {
test(get<0>(Test<2>::invoke));
return 0;
}
我遇到了链接错误,所以我尝试了这个:
template<int n>
struct Test {
static constexpr auto invoke = make_tuple(2, "test", 3.4);
};
// declare it outside the class
template<int n>
constexpr decltype(Test<n>::invoke) Test<n>::invoke;
template<typename T>
void test(T&& t) {
cout << t << endl;
}
int main() {
test(get<0>(Test<2>::invoke));
return 0;
}
但是我得到了这个奇怪的错误:
error: redefinition of 'invoke' with a different type: 'const decltype(Test<n>::invoke)' vs 'const std::tuple<int, const char *, double>'
不同的类型?? 显然,非模板版本的效果很好:
struct Test {
static constexpr auto invoke = make_tuple(2, "test", 3.4);
};
constexpr decltype(Test::invoke) Test::invoke;
template<typename T>
void test(T&& t) {
cout << t << endl;
}
int main() {
test(get<0>(Test::invoke));
return 0;
}
如何使模板版本正常工作?非常感谢
【问题讨论】:
-
我添加了 C++14,因为
make_tuple在此之前不是 constexpr。
标签: c++ templates c++14 static-members constexpr