[英]enable_if class member function with separate definition
I'm using enable_if
class member functions to iterate over a variational template argument.我正在使用
enable_if
类成员函数来迭代变分模板参数。 Here is a minimal example (without the actual variadic)这是一个最小的例子(没有实际的可变参数)
#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<>();
}
It works just fine but now I'm having problems with dependencies and decided to separate the declarations and definitions.它工作得很好,但现在我遇到了依赖问题,并决定将声明和定义分开。 I tried this:
我试过这个:
#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<>();
}
but GCC says that error: out-of-line definition of 'test' does not match any declaration in 'Test<size>'
.但 GCC 表示
error: out-of-line definition of 'test' does not match any declaration in 'Test<size>'
。 I managed to make it work by including definitions for both cases of test
.我设法通过包含
test
两种情况的定义来使其工作。 My question is: why doesn't this work?我的问题是:为什么这不起作用? Shouldn't the compiler only find one of the declarations for any
i
?编译器不应该只找到任何
i
的声明之一吗? Thank you in advance for any help!预先感谢您的任何帮助!
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() { /* ... */ }
The two member functions above are completely different, they just happen to have the same name test
.上面的两个成员函数完全不同,只是碰巧同名
test
。 They have different signatures and must be declared separately.它们具有不同的签名,必须单独声明。 It's similar to writing:
这类似于写作:
template<int i = 0>
int test() { }
template<int i = 0>
float test() { /* ... */ }
Would you expect to be able to have a single declaration for both of those in your class definition?您是否希望能够在您的类定义中为这两个声明单独声明?
You need to add the declaration inside the class with the matching signature您需要在类中添加具有匹配签名的声明
#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();
};
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<>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.