Johnny Pauling
Johnny Pauling

Reputation: 13417

Template can't accept an object as parameter

How come that the following code is wrong? Which type of parameters does a template accept?

class MyClass
{
    int var;
};

template <MyClass a> struct s
{

};

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


    return 0;
}

Upvotes: 0

Views: 85

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126442

Non-type template parameters are constrained, not everything can be used. In particular, they must be compile-time constants, which is not your case. Concerning your template definition:

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

See Paragraph 14.1/4 of the C++11 Standard:

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.

As you can see, user-defined types are not allowed. Concerning your template's instantiation, then:

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

See Paragraph 14.3.2/1 of the C++11 Standard:

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.

Upvotes: 4

Related Questions