Gui*_*cot 6 c++ templates static-members constexpr c++14
我的模板结构的静态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;
}
Run Code Online (Sandbox Code Playgroud)
我有链接错误,所以我尝试了这个:
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;
}
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了这个奇怪的错误:
error: redefinition of 'invoke' with a different type: 'const decltype(Test<n>::invoke)' vs 'const std::tuple<int, const char *, double>'
Run Code Online (Sandbox Code Playgroud)
不同的类型?显然,非模板版本工作得很好:
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;
}
Run Code Online (Sandbox Code Playgroud)
如何使模板版本正常工作?非常感谢你
如何使模板版本正常工作?
FWIW,你的方法在我的桌面上运行良好,它使用 g++ 4.8.4。
您可以使用:
template<int n>
constexpr decltype(make_tuple(2, "test", 3.4)) Test<n>::invoke;
Run Code Online (Sandbox Code Playgroud)
以下也适用于我的桌面:
template<int n>
struct Test {
static constexpr auto invoke = make_tuple(2, "test", 3.4);
typedef decltype(invoke) invoke_t;
};
template<int n>
constexpr typename Test<n>::invoke_t Test<n>::invoke;
Run Code Online (Sandbox Code Playgroud)