模板默认参数作为指向自身的指针

时间:2017-07-08 18:49:47

标签: c++ templates parameter-passing default

我正在尝试开发一个通用的树模板类,基本上,它代表了相同节点的层次结构。它需要2个模板参数,第一个是数据,第二个是引用另一个节点的类型(prev,next,parent,child)。默认情况下,我希望它是一个传统的节点指针,但为了我的目的,我还需要它是不同的东西(例如内存池的整数索引)。下面的代码无法编译。本能地,我觉得可以做到,但我不知道怎么做。任何人都可以提供这方面的见解吗?

template <typename U, typename TPTR = TreeNode_t<U>*>
class TreeNode_t
{
public:
    TPTR    prev;
    TPTR    next;
    TPTR    parent;
    TPTR    children;
    U m;
public:
    TreeNode_t() : prev(0), next(0), parent(0){}
    ~TreeNode_t(){}
    U &data() { return m; }
    const U &data() const { return m; }
    ...

具体来说,我通常会像这样实例化它:

TreeNode_t<double> tree1;

但是,有时我会这样想:

TreeNode_t<double, unsigned> tree2;

2 个答案:

答案 0 :(得分:5)

提供特殊默认值void并在类中使用类型:

template <typename U, typename TPTR = void>
class TreeNode_t
{
    using NodeType = std::conditional_t<std::is_same<void, TPTR>::value, TreeNode_t*, TPTR>;
public:
    NodeType    prev;
    NodeType    next;
    NodeType    parent;
    NodeType    children;
    U m;
// ...
};

答案 1 :(得分:0)

您不需要两个类型参数,因为可以从基类型推导出指针。当然,TreeNode_t没有在模板之前定义,因此它不能编译。

-(void)displayAd{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        //Background Thread
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullpageCampaign.mainImage]];

        dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"AdPage" bundle:nil];
            UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"adVC"];
            [vc setImage:[UIImage imageWithData:imageData]];
            [self presentViewController:vc animated:YES completion:^{}];
        });
    });
}
相关问题