c++ - 形成对 void 的引用

标签 c++ templates

我有一个模板类应该允许 void作为模板参数。此类确实有一个传递参数引用的函数,因此我执行了以下操作:

template <typename T>
struct trait
{
    typedef typename boost::conditional<
        boost::is_void<T>::value,
        void, T &
    >::type type;
};

template <typename T>
struct foo
{
    typename trait<T>::type ref()
    {
        // do something
    }
};

然而编译器声称我会形成对 void 的引用在 struct trait<void> 的实例化中.为什么会这样,我怎样才能实现我想要的?

最佳答案

好吧,当您说 T& 时,您显然在条件类型定义中形成了对 void 的引用。这似乎最好通过特化来处理:

template <typename T> struct trait { typedef T& type; };
template <> struct trait<void> { typedef void type; };

关于c++ - 形成对 void 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967767/

相关文章:

c++ - 如何检查在哪个专用模板中编译

c++ - "No matching function"模板函数接受回调

回调中生产者和消费者之间的 C++ 循环模板依赖

c++ - IE9 无法在 BHO 中的 HTMLWindow2 上触发 onscroll 事件

python - C++到Python的算法(径向对称变换)

c++ - 在模板参数推导过程中会发生什么?

c++ - 通话没有匹配功能?

c++ - Typedef 模板参数

c++ - 如何使用指向指针的指针存储 Polyomino 的对称性?

c++ - 展开操作期间遇到无效或未对齐的堆栈