use-defined转换为数组引用

时间:2015-09-05 13:47:26

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

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编译总是错误: 错误:类型&#39; int(&amp;)[20]&#39;的引用无效初始化来自&#39; S&#39;

的表达

为什么会失败?

1 个答案:

答案 0 :(得分:3)

typename id<T(&)[N]>::type中,TN位于非推断的上下文中。请改用别名模板:

template <typename T>
using id = T;

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