gpt4 book ai didi

c++ - 模板不能接受对象作为参数

转载 作者:行者123 更新时间:2023-11-27 23:18:02 25 4
gpt4 key购买 nike

下面的代码怎么错了?模板接受哪种类型的参数?

class MyClass
{
int var;
};

template <MyClass a> struct s
{

};

int main()
{
MyClass var;
struct s<var>;


return 0;
}

最佳答案

非类型模板参数有约束,不是什么都能用。特别是,它们必须是编译时常量,这不是你的情况。关于您的模板定义:

template <MyClass a> struct s
// ^^^^^^^
{
};

请参阅 C++11 标准的第 14.1/4 段:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

— integral or enumeration type,

— pointer to object or pointer to function,

— lvalue reference to object or lvalue reference to function,

— pointer to member,

— std::nullptr_t.

如您所见,不允许使用用户定义的类型。关于模板的实例化,则:

struct s<var>;
// ^^^ You most likely meant something like s<var> obj, but nevermind

参见 C++11 标准的第 14.3.2/1 段:

A template-argument for a non-type, non-template template-parameter shall be one of:

— for a non-type template-parameter of integral or enumeration type, a converted constant expression (5.19) of the type of the template-parameter; or

— the name of a non-type template-parameter; or

— a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage or a function with external or internal linkage, including function templates and function template-ids but excluding non-static class members, expressed (ignoring parentheses) as & id-expression, except that the & may be omitted if the name refers to a function or array and shall be omitted if the corresponding template-parameter is a reference; or

— a constant expression that evaluates to a null pointer value (4.10); or

— a constant expression that evaluates to a null member pointer value (4.11); or

— a pointer to member expressed as described in 5.3.1.

关于c++ - 模板不能接受对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com