c++ - 具有单独定义的enable_if类成员函数

标签 c++ c++11 enable-if class-members

我正在使用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/

相关文章:

C++ 相当于 .ToString()

c++ - 将可变参数传递给模板函数时出现编译错误

c++ - 如何使用默认构造函数参数对模板进行类型定义

c++ - Matlab 和 C++ 之间的转换

c++ - CONNECT 无法识别子类的 Qt 自定义 SLOT

c++ - 多个文件中的多个类 - C++/Arduino

c++11 - fbthrift (facebook thrift) 稳定版发布了吗?

c++ - 如果enable_if确定T是一个容器,则启用一个结构体?

c++ - 如何使用 std::enable_if 有条件地选择可变参数构造函数?

c++ - 模板特化和 enable_if 问题