【问题标题】:Template partial specialization on boolbool 的模板部分特化
【发布时间】: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 &lt;&gt; void Foo&lt;int, false&gt;::bar() {}Demo

标签: c++ templates template-specialization partial-specialization


【解决方案1】:

您的模板定义了一个类,而不是一个函数。这意味着您必须专门化该类,而不是类方法:

template < typename Object >
class Foo<Object, false> {
  void bar();
};

template < typename Object >
class Foo<Object, true> {
  void bar();
};

【讨论】:

  • 谢谢,看来我需要休息了。
  • 没问题。首先,一个人不应该在没有整夜睡眠和丰盛早餐的情况下编写 C++ 代码。你应该在计算机科学 101 中学到这一点。
  • @SamVarshavchik 好吧,我认为这里值得一提的是,不能在方法声明上对类进行 部分 特化,而像 this 这样的显式特化是完全有效的.
【解决方案2】:

另一种方法是分解 foo 并在单独的辅助类中处理 bar 的实现。这减少了实现 Foo 所需的重复次数。

例如:

template<class Object, bool Shared>
struct implement_bar;

template<class Object>
struct implement_bar<Object, true>
{
  void operator()(Object& o) const 
  {
    // do true thing with o
  }
};

template<class Object>
struct implement_bar<Object, false>
{
  void operator()(Object& o) const 
  {
    // do false thing with o
  }
};

template < typename Object, bool Shared = false >
class Foo {

  void bar()
  {
    return implement_bar<Object, Shared>()(*this);
  }
};

int main() {

  Foo<int> test;
  return 0;
}

【讨论】:

  • 哪个更好: split 还是 std::enable_if ?
  • @MathieuVanNevel 哪个最容易阅读、理解和维护。
猜你喜欢
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多