在非类型模板参数上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

提问人:oarfish 提问时间:10/2/2023 最后编辑:Oerstedoarfish 更新时间:10/2/2023 访问量:51

问:

尝试将模板拆分为声明和定义以方便阅读时,会出现此问题。

考虑这个 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 的解决方案会更好。

C++ 模板 函数定义 成员函数

评论

1赞 Oersted 10/2/2023
嗨,问题标题和标签可能具有误导性(这似乎更像是一个不合时宜的定义问题),否则,这对我来说似乎是合法的。
0赞 oarfish 10/2/2023
你能为这个问题建议更好的标签吗?
0赞 Oersted 10/2/2023
我提议进行编辑。我们将看看它是否被接受。NB MarekR 评论将解决您的问题,但我仍然有兴趣了解为什么您的实现不起作用。
3赞 Jarod42 10/2/2023
一旦拼写错误修复,这里就可以工作(->)。N == 6N2 == 6
1赞 Marek R 10/2/2023
错别字:重复的定义(在类内和类外)和在定义中使用声明位置 - 使其不一致。godbolt.org/z/GW7Pa1Wfv 投票接近错别字。N2N

答: 暂无答案