jackhab
jackhab

Reputation: 17698

Passing enum as template paramer

Why the following template function

template<typename T>
bool isEqual(const T &v0, const T &v1)
{
    return v0 == v1;
}

does not compile when v1 and v2 are enumerated? How can should I write a template function which compares variable with enum: isEqual(color, RED)?

template<typename T>
bool isEqual(const T &v0, const T &v1)
{
    return v0 == v1;
}


int main()
{
    enum Enum
    {
        E1,
        E2,
        E3
    } v1, v2;

    v1 = E1;
    v2 = E1;

    isEqual(v1, v2);

}

TestProject/main.cpp: In function 'int main()': TestProject/main.cpp:31: error: no matching function for call to 'isEqual(main()::Enum&, main()::Enum&)'

Upvotes: 0

Views: 144

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

It probably means that your compiler is out of date.

Before C++11, types without linkage (e.g. types declared within a function) couldn't be used as template arguments. This rather odd restriction has now been removed.

Your example should compile if you either move the enum declaration to namespace scope (giving it external linkage), or use a modern compiler: http://ideone.com/QZQjHI

Upvotes: 4

Related Questions