使用不完整类型(SFINAE)无效

Kip*_*aki 5 c++ templates sfinae template-specialization

我试图在模板化结构中使用一些SFINAE.我将我的问题减少到以下,并可以使这项工作:

template<bool mybool>
struct test {
    void myfunc();
};

template<bool mybool>
void test<mybool>::myfunc() {
    std::cout << "test true" << std::endl;
}
template<>
void test<false>::myfunc() {
    std::cout << "test false" << std::endl;
}

int main(int argc, char ** argv) {
    test<true> foo;
    test<false> bar;
    foo.myfunc();
    bar.myfunc();
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我得到结果:

test true
test false
Run Code Online (Sandbox Code Playgroud)

但是,如果我想考虑我struct test的多个模板参数,我尝试调整上面这样:

template<int myint, bool mybool>
struct test {
    void myfunc();
};

template<int myint, bool mybool>
void test<myint,mybool>::myfunc() {
    std::cout << "test true" << std::endl;
}
template<int myint>
void test<myint,false>::myfunc() { 
//error: invalid use of incomplete type 'struct test<myint, false>'
    std::cout << "test false" << std::endl;
}

int main(int argc, char ** argv) {
    test<1,true> foo;
    test<1,false> bar;
    foo.myfunc();
    bar.myfunc();
}
Run Code Online (Sandbox Code Playgroud)

我无效使用不完整类型'struct test'.

我走错了方向吗?有办法做我想做的事吗?谢谢你的帮助!

For*_*veR 6

你不能部分专门化成员函数,你应该partially specialize完整的struct.以下示例将正常工作

template<int myint, bool mybool>
struct test {
    void my_func();
};

template<int myint, bool mybool>
void test<myint,mybool>::my_func() {
    std::cout << "test true" << std::endl;
}

template<int myint>
struct test<myint, false> {
   void my_func();
};

template<int myint>
void test<myint,false>::my_func() { 
//error: invalid use of incomplete type 'struct test<myint, false>'
    std::cout << "test false" << std::endl;
}

int main(int argc, char ** argv) {
    test<1,true> foo;
    test<1,false> bar;
    foo.my_func();
    bar.my_func();
}
Run Code Online (Sandbox Code Playgroud)