我正在使用enable_if
用于迭代变分模板参数的类成员函数。这是一个最小的示例(没有实际的变量)
#include <iostream>
template<int size> class Test {
public:
template<int i = 0> typename std::enable_if<i == size, void>::type test() {}
template<int i = 0> typename std::enable_if<i < size, void>::type test() {
std::cout << "cycle: " << i << '\n';
test<i + 1>();
}
};
int main(int, char**) {
Test<10> a;
a.test<>();
}
它工作得很好,但现在我遇到了依赖项问题,并决定将声明和定义分开。我试过这个:
#include <iostream>
template<int size> class Test {
public:
template<int i = 0> void test();
};
template<int size>
template<int i> typename std::enable_if<i == size, void>::type Test<size>::test() {}
template<int size>
template<int i> typename std::enable_if<(i < size), void>::type Test<size>::test() {
std::cout << "cycle: " << i << '\n';
test<i + 1>();
}
int main(int, char**) {
Test<10> a;
a.test<>();
}
但是 GCC 说 error: out-of-line definition of 'test' does not match any declaration in 'Test<size>'
。我设法通过包含 test
两种情况的定义来使其工作。 。我的问题是:为什么这不起作用?编译器不应该只找到任何 i
的声明之一吗? ?预先感谢您的帮助!
最佳答案
template<int i = 0>
typename std::enable_if<i == size, void>::type test() { }
template<int i = 0>
typename std::enable_if<i < size, void>::type test() { /* ... */ }
上面的两个成员函数完全不同,它们只是碰巧具有相同的名称test
。它们有不同的签名,必须单独声明。这类似于编写:
template<int i = 0>
int test() { }
template<int i = 0>
float test() { /* ... */ }
您是否希望能够在类定义中对这两个内容进行单一声明?
关于c++ - 具有单独定义的enable_if类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109914/