c++-命名的模板参数

c++-命名的模板参数,第1张

c++-命名的模板参数

场景如下
template<
typename PolicySetter1 = DefaultPolicyArgs,
typename PolicySetter2 = DefaultPolicyArgs,
typename PolicySetter3 = DefaultPolicyArgs,
typename PolicySetter4 = DefaultPolicyArgs>
class BreadSlicer;
它四个参数,且都有默认值
如果我们想修改 PolicySetter4的值, 我们不得不这么做
BreadSlicer
就是重复前面的每一个默认值,然后设置新值,那么有没有一种方式能让我们直接修改值而不用管前面的默认参数呢

下面带来这种技巧

#include 
#include 
#include 
#include 

using namespace std;

class A {
 public:
    static void doSomething() {
        cout << "A::doSomething" << endl;
    }
};

class B {
 public:
    static void doSomething() {
        cout << "B::doSomething" << endl;
    }
};

class C {
 public:
    static void doSomething() {
        cout << "C::doSomething" << endl;
    }
};

class D {
 public:
    static void doSomething() {
        cout << "D::doSomething" << endl;
    }
};

class AA {
 public:
    static void doSomething() {
        cout << "**************************** AA::doSomething" << endl;
    }
};

class BB {
 public:
    static void doSomething() {
        cout << "**************************** BB::doSomething" << endl;
    }
};

class CC {
 public:
    static void doSomething() {
        cout << "**************************** CC::doSomething" << endl;
    }
};

class DefaultPolicies {
 public:
    using P1 = A;
    using P2 = B;
    using P3 = C;
    using P4 = D;
};

template
class PolicySetter1 : virtual public DefaultPolicies {
 public:
    using P1 = Policy;
};

template
class PolicySetter2 : virtual public DefaultPolicies {
 public:
    using P2 = Policy;
};

template
class PolicySetter3 : virtual public DefaultPolicies {
 public:
    using P3 = Policy;
};

template
class PolicySetter4 : virtual public DefaultPolicies {
 public:
    using P4 = Policy;
};

template
class Discriminator : public base {
};

template
class PolicySelector
        : public Discriminator, public Discriminator, public Discriminator,
          public Discriminator {
};

class DefaultPolicyArgs : virtual public DefaultPolicies {
};

template<
        typename PolicySetter1 = DefaultPolicyArgs,
        typename PolicySetter2 = DefaultPolicyArgs,
        typename PolicySetter3 = DefaultPolicyArgs,
        typename PolicySetter4 = DefaultPolicyArgs>
class BreadSlicer {
    using Policies = PolicySelector;

 public:
    void A() {
        Policies::P1::doSomething();
    }

    void B() {
        Policies::P2::doSomething();
    }

    void C() {
        Policies::P3::doSomething();
    }

    void D() {
        Policies::P4::doSomething();
    }

    void show() {
        A();
        B();
        C();
        D();
        cout << endl;
    }
};

int main() {
    BreadSlicer<> ex;
    ex.show();

    BreadSlicer>
            ex4;
    ex4.show();
}

我们修改了 第四个和第二个参数, 甚至第4个参数在第2个前面

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5115460.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存