rara
rara

Reputation: 27

explicit template instantiation in main function

I have some toy codes as follow:

#include <iostream>

using namespace std;
template<typename T>
class MyClass{
    T t;
};
template class MyClass<int>;
int main()
{
    //template class MyClass<int>;
    return 0;
}

and:

#include <iostream>

using namespace std;
template<typename T>
class MyClass{
    T t;
};
//template class MyClass<int>;
int main()
{
    template class MyClass<int>;
    return 0;
}

template class MyClass<int>;inside the main() function didn't work.The error is error: expected primary-expression before 'template' But the same statement outside the main() function works.Why this happen?

Upvotes: 2

Views: 203

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153810

I'd think this statement in 14.7.2 [temp.explicit] paragraph 3 means that explicit template instantiations have to appear at namespace scope:

... An explicit instantiation shall appear in an enclosing namespace of its template. ...

The implication is that you cannot explicitly instantiated templates with function-locale types. Since the intention of explicit template instantiations is avoiding multiple instantiations of templates repeatedly used with a just a few types, e.g., instantiating the stream types, this restriction isn't constraining.

Upvotes: 2

Related Questions