提问人:oarfish 提问时间:10/2/2023 最后编辑:Oerstedoarfish 更新时间:10/2/2023 访问量:51
在非类型模板参数上enable_if模板类的模板成员函数时,在行外定义该函数时出现问题
issue with enable_if a template member function of template class, on a non-type template parameter, when defining it out of line
问:
尝试将模板拆分为声明和定义以方便阅读时,会出现此问题。
考虑这个 MWE
#include <type_traits>
template <typename T1, typename T2, int N = 6>
struct Foo {
template <int N2 = N, typename std::enable_if<N2 == 6, bool>::type = true>
Foo(int i);
template <int N2 = N, typename std::enable_if<N2 != 6, bool>::type = true>
Foo(double d);
};
template <typename T1, typename T2, int N>
template <int N2, typename std::enable_if<N == 6, bool>::type >
Foo<T1, T2, N>::Foo(int i){}
template <typename T1, typename T2, int N>
template <int N2, typename std::enable_if<N != 6, bool>::type >
Foo<T1, T2, N>::Foo(double d){}
int main(int argc, char** argv) {
Foo<int, double, 3> foo1(4.5);
Foo<int, double, 6> foo2(4);
return 0;
}
我想让类模板有一个构造函数,如果没有,则有另一个构造函数。
上面的代码在将构造函数主体与声明放在一起时有效,但是在拆分它们时我似乎找不到正确的语法。N == 6
Godbolt 的编译器错误是
<source>:15:17: error: out-of-line definition of 'Foo<T1, T2, N>' does not match any declaration in 'Foo<T1, T2, N>'
Foo<T1, T2, N>::Foo(int i){}
^~~
<source>:19:17: error: out-of-line definition of 'Foo<T1, T2, N>' does not match any declaration in 'Foo<T1, T2, N>'
Foo<T1, T2, N>::Foo(double d){}
^~~
2 errors generated.
Compiler returned: 1
我在这里犯了什么错误?
如果需要,我可以使用 C++20,但 17 或 14 的解决方案会更好。
答: 暂无答案
评论
N == 6
N2 == 6
N2
N