【问题标题】:use-defined conversion to array reference使用定义转换为数组引用
【发布时间】:2015-09-05 13:47:25
【问题描述】:
template <typename T>
struct id
{
    typedef T type;
};

class S{
public:

    template<typename T, int N> 
    operator typename id<T(&)[N]>::type ();

};

void f(int(&)[20]) {}
void g(S s) { cout << typeid(f(s)).name(); }

gcc 编译总是报错: 错误:从类型“S”的表达式中对类型“int (&)[20]”的引用的初始化无效

为什么会失败?

【问题讨论】:

    标签: c++ c++11 type-conversion type-deduction


    【解决方案1】:

    typename id&lt;T(&amp;)[N]&gt;::typeTN 中处于非推断上下文中。改用别名模板:

    template <typename T>
    using id = T;
    
    class S{
    public:
        template<typename T, int N> 
        operator id<T(&)[N]> ();
    };
    

    【讨论】:

    • 有非C++11的解决方案吗?
    • 为什么转换函数不允许使用尾随返回类型?很明显,运算符 auto 是为其他用途而保留的,但尾随返回类型的变体似乎并没有阻碍任何这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 2019-12-19
    相关资源
    最近更新 更多