简体   繁体   English

为什么不允许使用此默认模板参数?

[英]Why is this default template parameter not allowed?

I have the following class: 我有以下课程:

template <typename Type = void>
class AlignedMemory {
public:
    AlignedMemory(size_t alignment, size_t size)
        :   memptr_(0) {
        int iret(posix_memalign((void **)&memptr_, alignment, size));
        if (iret) throw system_error("posix_memalign");
    }
    virtual ~AlignedMemory() {
        free(memptr_);
    }
    operator Type *() const { return memptr_; }
    Type *operator->() const { return memptr_; }
    //operator Type &() { return *memptr_; }
    //Type &operator[](size_t index) const;
private:
    Type *memptr_;
};

And attempt to instantiate an automatic variable like this: 并尝试实例化一个自动变量,如下所示:

AlignedMemory blah(512, 512);

This gives the following error: 这会出现以下错误:

src/cpfs/entry.cpp:438: error: missing template arguments before 'blah' src / cpfs / entry.cpp:438:错误:'blah'之前缺少模板参数

What am I doing wrong? 我究竟做错了什么? Is void not an allowed default parameter? void不是允许的默认参数吗?

I think that you need to write: 我想你需要写:

AlignedMemory<> blah(512, 512);

See 14.3 [temp.arg] / 4: 见14.3 [temp.arg] / 4:

When default template-arguments are used, a template-argument list can be empty. 使用默认模板参数时模板参数列表可以为空。 In that case the empty <> brackets shall still be used as the template-argument-list . 在这种情况下,空<>括号仍应用作模板参数列表

Your syntax is wrong: 你的语法错了:

AlignedMemory blah(512, 512); //wrong syntax

Correct syntax is this: 正确的语法是这样的:

AlignedMemory<> blah(512, 512); //this uses "void" as default type!

The error message itself gives this hint. 错误消息本身给出了这个提示。 Look at it again: 再看一遍:

src/cpfs/entry.cpp:438: error: missing template arguments before 'buf' src / cpfs / entry.cpp:438:错误:'buf' 之前 缺少模板参数

PS: I'm sure 'buf' is a typo. PS:我确定'buf'是一个错字。 You wanted to write 'blah' - the name of your variable! 你想写'blah' - 变量的名字!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM