【发布时间】:2016-12-01 23:14:53
【问题描述】:
我认为这是一个非常基本的问题,但我无法找到答案,即使在 StackOverflow 上也是如此。很抱歉,如果您想在阅读本文时打我。
我只想对 bool 值进行部分专业化:
template < typename Object, bool Shared = false >
class Foo {
void bar();
};
template < typename Object >
void Foo<Object, true>::bar() {}
template < typename Object >
void Foo<Object, false>::bar() {}
int main() {
Foo<int> test;
return 0;
}
我认为这个想法是正确的,但我在这段代码中遗漏了一些东西(可能真的很愚蠢):
Test3.cpp:8:30: error: invalid use of incomplete type ‘class Foo<Object, true>’
void Foo<Object, true>::bar() {
^
Test3.cpp:2:7: note: declaration of ‘class Foo<Object, true>’
class Foo {
^~~
Test3.cpp:13:31: error: invalid use of incomplete type ‘class Foo<Object, false>’
void Foo<Object, false>::bar() {
^
Test3.cpp:2:7: note: declaration of ‘class Foo<Object, false>’
class Foo {
【问题讨论】:
-
你不应该尝试专业化一门课程吗?看起来您正在尝试定义一个作为专业化一部分的函数。
-
你不能部分特化一个函数/方法,但你可以完全特化它:
template <> void Foo<int, false>::bar() {}Demo
标签: c++ templates template-specialization partial-specialization