2016-06-09 76 views
0

我有以下的模板类:使用模板类不完全类型为void

template <typename T> 
class myClass 
{ 
public: 
    // Many methods... 
protected: 
private: 
    T attribute 
    // Other attributes. 
}; 

实例化myClass<void>类型的对象不起作用,因为void attribute。 你能否给我一些提示,以便能够使用myClass<void>类型的对象而不需要专门研究整个班级。由于它有许多依赖类型T的成员函数,因此将其专门化会导致代码重复。

+3

你想要什么你'属性类型是? –

+0

我真的不明白这是什么意思。根据您所展示的内容,模板类型的唯一用途就是导致问题的原因。 – 2016-06-09 19:35:26

+0

我希望能够实例化一个类型为“myClass ”的对象,但在这种情况下,'attribute'的类型是'void',这是不可能的。 – baboulinet

回答

2

您可以通过使用自定义类型和专业是推迟整个问题:

template<typename T> 
struct my_type_t 
{ 
    using type = T; 
}; 

template<> 
struct my_type_t<void> 
{}; 

template<typename T> 
using my_type = typename my_type_t<T>::type; 

template <typename T> 
class myClass 
{ 
public: 
    // Many methods... 
protected: 
private: 
    my_type<T> attribute 
    // Other attributes. 
}; 

那么至少你不必再重复类的全部剩余部分。

但它可能没有多大意义,因为你一定想在某处使用该类型。所以你必须进一步专门化这些地方。

3

创建一个包含模板基类的属性,专门它void,并从它继承:

namespace detail //Warn end user that he should not use stuff from here 
{ 
    template <typename T> 
    struct myClass_base 
    { 
     T attribute; 
    }; 

    template <> 
    struct myClass_base<void> 
    {}; //No attribute at all 
} 

template <typename T> 
class myClass: private detail::myClass_base<T> 
{ 
    //rest of definition 
}; 

这将使myClass类型实例化时,它缺乏attributevoid

相关问题