前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++奇淫巧技之SFINAE

C++奇淫巧技之SFINAE

作者头像
zhuanxu
发布2018-08-23 13:05:53
5220
发布2018-08-23 13:05:53
举报
文章被收录于专栏:进击的程序猿

SFINAE 技术,即匹配失败不是错误,英文Substitution Failure Is Not An Error,其作用是当我们在进行模板特化的时候,会去选择那个正确的模板,避免失败

看个具体的例子:

代码语言:javascript
复制
long multiply(int i, int j) { return i * j; }

template <class T>
typename T::multiplication_result multiply(T t1, T t2)
{
    return t1 * t2;
}
int main(void)
{
    multiply(4,5);
}

当我们编译的时候,会去匹配模板 multiply,但是由于我们不知道multiplication_result,根据 Substitution Failure Is Not An Error ,于是我们就去选择函数 multiply

这种技术在代码中的一个大的用途就是在编译时期来确定某个 type 是否具有我们需要的性质,看代码

代码语言:javascript
复制
template <class T>
struct is_pointer
{
    template <class U>
    static char is_ptr(U *);

    template <class X, class Y>
    static char is_ptr(Y X::*);

    template <class U>
    static char is_ptr(U (*)());

    static double is_ptr(...);

    static T t;
    enum { value = sizeof(is_ptr(t)) == sizeof(char) };
};

struct Foo {
    int bar;
};

void testTypeCheck() {
    typedef int * IntPtr;
    typedef int Foo::* FooMemberPtr;
    typedef int (*FuncPtr)();

    printf("%d\n",is_pointer<IntPtr>::value);        // prints 1
    printf("%d\n",is_pointer<FooMemberPtr>::value);  // prints 1
    printf("%d\n",is_pointer<FuncPtr>::value);       // prints 1
}

通过定义4个重载的 is_ptr函数,3个是接受不同的指针参数,另一个则包括了其他的所有参数, IntPtr 是一个变量指针 FooMemberPtr 是一个成员属性指针 FuncPtr 是一个函数指针

接着我们来看下 muduo 库中的一段代码:

代码语言:javascript
复制
template<typename T>
struct has_no_destroy {
    template<typename C>
    static char test(decltype(&C::no_destroy));


    template<typename C>
    static int32_t test(...);

    const static bool value = sizeof(test<T>(0)) == 1;
};
// 其作用就是用来判断是否有 no_destroy 函数

struct A {

};

struct B {
    void no_destroy(){}
};
struct C {
    int no_destroy;
};

struct D : B {

};

void testNoDestroy() {
    printf("%d\n",has_no_destroy<A>::value);
    printf("%d\n",has_no_destroy<B>::value);
    printf("%d\n",has_no_destroy<C>::value);
    printf("%d\n",has_no_destroy<D>::value);
}

其作用主要是判断是否有no_destroy,并且在继承上也成立,但是继承在不同的gcc版本上不一定成立,具体可以看:http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions

code地址:https://github.com/zhuanxuhit/happy-code/tree/master/src/idioms

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.03.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档