【问题标题】:specialize a template with expression parameter使用表达式参数专门化模板
【发布时间】:2012-08-15 04:24:09
【问题描述】:

我有这样的课:

template <class T>
class Foo;

我想专攻

template <>
class Foo < size_t N >;

但这不适合我:

我的主要是这样的:

Foo<int> p;  // OK
Foo<15> p2;  // fails to compile

我错过了什么?

【问题讨论】:

  • 您的第二个Foo 不是特化,它是一个完全不同的模板(它不采用相同类型的参数)。与函数不同,模板不能重载(不过,我不知道这种限制是否有充分的理由。如果有人有解释,我会很高兴听到。)。

标签: c++ templates


【解决方案1】:

您不能 - 您的模板始终采用一个类型参数。专业化只能比这更特殊,但不能不同(因此得名)。

也许你可以使用辅助模板来存储值信息:

template <typename T, T Val> struct ValueWrapper { };

template <typename T> struct Foo;

templaet <typename T, T Val> struct Foo<ValueWrapper<T, Val>>
{
    typedef T type;
    static type const value = Val;

    // ...
};

用法:

Foo<char> x;
Foo<ValueWrapper<int, 15>> y;

【讨论】:

【解决方案2】:

共有三种模板参数:代表类型的那些(例如class Ttypename T),代表非类型的那些(例如int Nsize_t N),以及代表一个模板(例如template &lt;class T2&gt; class T)。

为您的模板定义的参数属于第一类(类型参数),但特化假定为第二类(非类型参数)。那是行不通的。特化的参数必须与主模板定义的对应参数同种。

【讨论】:

  • 为了正确理解,这里有一个带有冗余模板参数的示例:ideone.com/fxKM6
  • @jogojapan: “三种模板” - 更多的是各种模板参数的情况......任何给定的模板都可以混合和匹配这些“种类”的参数。
  • @TonyDelroy 是的。我的回答隐含地假设只有一个模板参数,因为在 OP 的示例中就是这种情况。我已经改写了。谢谢。
【解决方案3】:

您可以使用中间类来专门化该类:

template <class T>
class Foo
{
public:
  static const bool is_number = false;
};
template <size_t number>
struct ic
{};
template <size_t N>
class Foo < class ic<N> >
{
public:
   static const bool is_number = true;
   size_t getN() const
   {
      return N;
   } 
};

int main()
{
   Foo<int> p;  
   Foo<ic<15> > p2;  
   cout << "p.is_number = " << p.is_number << endl;
   cout << "p2.is_number = " << p2.is_number  << endl;
   cout << "p2.getN() = " << p2.getN() << endl;
   return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多