c++11禁止用某个模板的方法 ,结合std::enable_if 实现

使用场景:

有多个构造函数,也同时用模板实现了一个可变参数的构造函数,现在想分别调用不同的构造函数,但可变参数构造函数不加条件,则所有初始化都会调用此可变参数构造函数,这是模板自动匹配原则导致的,因此在某些情况下想禁止此可变参数的构造函数,用其他构造函数,怎么实现呢?现在模板结合std::enable_if可以实现这样的需求。

std::enable_if的作用可以网上找相关说明,下面是 c++11禁止用某个模板的方法,本例子可以主要对可变参数的模板实现

代码实现:

#include <type_traits>
#include <iostream>
#include <memory>

class B {
public:
    B() { //没有参数的构造函数
        std::cout << "B init 0 param" << std::endl;
    }

    B(std::string ptr) { //1个参数的构造函数
        std::cout << "B init 1 param" << std::endl;
    };

    B(std::string sharedPtr, std::string sharedPtr1) { //2个参数的构造函数
        std::cout << "B init 2 param" << std::endl;
    }

    //3个参数的构造函数
    B(std::string sharedPtr, std::string sharedPtr1, std::string sharedPtr2) {
        std::cout << "B init 3 param string " << std::endl;
    }

    //可变参数的构造函数,只有参数大于3个才用此构造函数,假如不用std::enable_if加条件,则所有初始化都会调用此构造函数,模板匹配原则
    template<class... Args, typename std::enable_if<(sizeof...(Args) > 3)>::type...>
    B(Args&&... args) {
        fun1(std::forward<Args>(args)...);
        std::cout << "B init n parm" << std::endl;
    }

    ~B() {
        std::cout << "~B" << std::endl;
    };

    template<class U, class T>
    void fun1(U a, U b, U c, T d) {
        std::cout << "----fun1 template a:" << a << ",d:" << d << std::endl;
        funceb<T>(d);
    }
    
    template <typename F>
    typename std::enable_if<(sizeof(F) > 4)>::type funceb(F a)
    {
        std::cout << "----2222 funceb template a:" << a << std::endl;
    }
 

public:
    std::string a;
};

class D;
class C {
public:
    C(){
        std::cout << "0 C init" << std::endl;
    };

    //可变参数的类型都不一样的实现方式
    template<class... Args>
    void func(Args&&... args) {
        d_ptr = std::make_shared<D>(std::forward<Args>(args)...);
    }

    ~C() {};

private:
    std::shared_ptr<D> d_ptr;
};

class D {
public:
    D(){
        std::cout << "0 D init" << std::endl;
    };

    D(int a, std::string s, float f) {
        std::cout << "1 D init s:" << s << std::endl;
    };
    ~D() {};
};

int main()
{
    B b0;//用没有参数的构造函数
    B b("a1" ,"a2");//用只有两个参数的构造函数
    B b1(100 , 200 , 200, "hello"); //用可变参数的构造函数

    C c;
    c.func(1, "aaaaddddd", 2.0);//可变参数的多种数据类型的方式
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值