【问题标题】:different class implementations based on template parameter基于模板参数的不同类实现
【发布时间】:2014-06-30 13:17:07
【问题描述】:

我想这对于知道模板的人来说是微不足道的......

假设我们想要这个模板类的两个不同实现,取决于 N 的值:

template <int N>
class Foo {
    ...
};

例如:

template <int N>
class Foo {
    ... // implementation for N <= 10
};

template <int N>
class Foo {
    ... // implementation for N > 10
};

我们如何在 C++11 中做到这一点?

【问题讨论】:

    标签: c++ templates c++11 template-meta-programming


    【解决方案1】:

    使用带有默认值的额外模板参数来区分大小写:

    template <int N, bool b = N <= 10>
    class Foo;
    
    template <int N>
    class Foo<N, true> {
      ...  // implementation for N <= 10
    };
    
    template <int N>
    class Foo<N, false> {
      ...  // implementation for N > 10
    };
    

    【讨论】:

    • 使用std::conditional&lt;N&lt;=10, FooBaseLess&lt;N&gt;, FooBaseMore&lt;N&gt;&gt;::type 作为基类也可以。但这要整洁得多,+1。
    • 感谢您:1. 简洁且非常有用的回答,2. 不问“您为什么要这样做?”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多