如何在转换运算符中使用std :: enable_if? [英] how can I use std::enable_if in a conversion operator?

查看:153
本文介绍了如何在转换运算符中使用std :: enable_if?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我希望我的范围类型可以隐式转换从 Range< const char> Range< const unsigned char> 。 std :: enable_if似乎不可能,因为该函数没有参数,没有返回。

Basically I want my range type to be implicitly convertible from Range<const char> to Range<const unsigned char>. std::enable_if seems impossible because the function takes no arguments and has no return. Whats the work around?

这里基本上是我尝试过的:

Here is basically what I tried:

template<typename T>
class Range{
    T* begin_;
    T* end_;
public:
    Range(T* begin,T* end):begin_{begin},end_{end}{}
    template<int N>
    Range(T (&a)[N]):begin_{static_cast<T*>(&a[0])},end_{static_cast<T*>(&a[N-1])}{}
    T* Begin(){return begin_;}
    T* End(){return end_;}
    operator typename std::enable_if<std::is_same<T,const char>::value,Range<const unsigned char>&>::Type (){
        return *reinterpret_cast<Range<const unsigned char>*>(this);
    }
};


推荐答案

将其设为带有虚拟参数的模板,默认为T - 这是推迟类型推导到函数实例化的点,否则SFINAE 无法运行

Make it a template with a dummy parameter that defaults to T - this is to postpone type deduction to the point where the function gets instantiated, otherwise SFINAE doesn't work. Then you do the check you want in default value of another parameter.

template<
    typename U = T,
    typename = typename std::enable_if< std::is_same<U,const char>::value >::type
>
operator Range<const unsigned char>() {
    return *reinterpret_cast<Range<const unsigned char>*>(this);
}

这篇关于如何在转换运算符中使用std :: enable_if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆