【发布时间】:2018-03-05 11:52:27
【问题描述】:
我正在使用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 的声明之一吗?提前感谢您的帮助!
【问题讨论】:
-
如果你想在编译时迭代数字,你可能会对
std::index_sequence替换std::enable_if感兴趣。 that 之类的东西(也可以在 C++11 中完成) -
那太好了,我会切换到那个。非常感谢! (我从来没有见过省略号的用法,真的很酷)
标签: c++ c++11 enable-if class-members