Explicit specialization of non-class, non-function members of a class template - c++

Look at the code:
template <class x> struct Foo
{
int getX(x *p) { return(0); }
enum E12 { a };
};
template <> int Foo<int>::getX(int*)
{
return(-15);
}
template <> enum Foo<int>::E12
{
a, b, c
}
As it was discussed in Cannot overload function, the first specialization is legal and even works in MSVC. While the second specialization for enum does not even want to compile, saying "error C2988: unrecognizable template declaration/definition".
It seems to me that C++ is making relaitively unlogical exception for methods. Enum is just an example. The same thing can be applied to member classes, typedefs, etc.
I will be happy is some body will comment on this.

This is a very obscure new feature of C++11. File a bug report with Microsoft, although it is unlikely it will be given priority as almost nobody is aware this is allowed. The correct syntax would be
template <class x> struct Foo
{
int getX(x *p) { return(0); }
enum E12 { a };
};
template <> int Foo<int>::getX(int*)
{
return(-15);
}
template <> enum Foo<int>::E12
{
a, b, c
};
I've filed a bug with GCC. Can someone test on recent Clang?
In C++03, only classes and functions may be explicitly specialized. From the standard, C++03 14.7.3/1:
An explicit specialization of any of the following:
function template
class template
member function of a class template
static data member of a class template
member class of a class template
member class template of a class or class template
member function template of a class or class template
can be declared by a declaration introduced by template<>
A member enum is not such a case. (Generally speaking, an enum type is always defined only once at its first declaration.)
To obtain a templated enum or typedef, you can wrap it in a class template. In your case, it would be a member class template of Foo. Such a construct is called a metafunction.
C++11 also has alias templates, which are like templated typedefs, but they cannot be explicitly specialized.
The policy of only allowing classes and functions to be specialized, and then allowing such templates to encapsulate other things like enum and typedef, seems more consistent to me than allowing direct specialization of enum. But, perhaps the language is going in your preferred direction.

Related

Static assert in template specialization fails even if it is not instantiated

The following code compiles fine:
#include <type_traits>
template <typename T> struct dependent_true : std::true_type { };
template <typename T> struct dependent_false : std::false_type { };
template <bool B = false>
class X { static_assert(dependent_false<X>::value); };
template <>
class X<true> { static_assert(dependent_true<X>::value); };
int main() {
X<true> x;
}
That is, the static_assert in the primary template is not evaluated. On the contrary, if I switch to:
template <bool B = false>
class X { static_assert(dependent_true<X>::value); };
template <>
class X<true> { static_assert(dependent_false<X>::value); };
int main() {
X<false> x;
}
Then, the static assertion in template specialization fails, even if it is not instantiated. I just wonder why. I observed this behavior with GCC 8 and Clang 6 (-std=c++17).
Live demo: https://wandbox.org/permlink/MOWNLnGMgmuDA2Ht
template <> class X<true> {/* ... */}; - is not a template anymore.
[temp.expl.spec]/5
A member of an explicitly specialized class is not implicitly
instantiated from the member declaration of the class template;
instead, the member of the class template specialization shall itself
be explicitly defined if its definition is required. In this case, the
definition of the class template explicit specialization shall be in
scope at the point at which the member is defined. The definition of
an explicitly specialized class is unrelated to the definition of a
generated specialization. That is, its members need not have the same
names, types, etc. as the members of a generated specialization.
Members of an explicitly specialized class template are defined in the
same manner as members of normal classes, and not using the template<>
syntax. The same is true when defining a member of an explicitly
specialized member class. However, template<> is used in defining a
member of an explicitly specialized member class template that is
specialized as a class template.
The specialization is just like a regular class. It's not a template, and nothing is dependent. Therefore dependent_false<X>::value is just a constant expression that evaluates immediately to false. So the static assertion is immediately triggered.
Even non-instantiated template parts should be valid C++ code. static_assert(false) makes the program ill-formed. So you have your specialization with static_assert which is known on compile time to be false and your program becomes ill-formed. You have no non-resolved template parameters on your class which is used in static_assert to make compiler wonder; it knows exactly that it is false.
The same goes to if constexpr, you also can't use static_assert with expressions known to be false even if the part where this static_assert is located always gets discarded.

template class specialization : template-id does not match any template declaration

I'm trying to use templates, but couldn't understand what is wrong with below code.
solve.h
#include "nlp.h"
#include "Ipopt_solve.h"
enum algo_type {IPOPT =1, SQP};
template<int ALG>
class solve
{
public:
solve()
{
}
};
template<>
class solve<IPOPT>
{
public:
solve(nlp*);
private:
Ipopt_solve m_ipopt;
};
solve.cpp
template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
Ipopt_solve is a sub-class of an abstract class TNLP. Ipopt_solve is initialized with a reference to nlp class.
from main.cpp
nlp problem(&model);
solve<IPOPT> solution(&problem);
I'm getting the error like shown below.
error: template-id 'solve<>' for 'solve<1>::solve(nlp*)' does not match any template declaration
solve::solve(nlp* problem): m_ipopt(problem)
This declaration in its original form
template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
is formally valid by itself. However, it is not doing what you think it is doing. This declaration declares an explicit specialization for a member of the main template
template<int ALG>
class solve
{
...
It has no relation to your explicit specialization
template<>
class solve<IPOPT>
{
...
The compiler is trying to specialize constructor solve<ALG>::solve(nlp* problem) of the main template. However, the main template has no such constructor. Hence the error message, that tells you exactly that: the compiler does not understand what constructor you are trying to specialize, it cannot find the matching member in the main template.
For example, you can use this syntax to explicitly specialize the default constructor of the main template
template<>
solve<SQP>::solve()
{
// Specialized code for `solve<SQP>`'s default constructor
}
This will compile fine since the main template does indeed have such constructor. (Note that you don't have to explicitly specialize the whole class for that, you can just explicitly specialize the constructor.)
Your intent was, obviously, completely different: to provide definition for the constructor in the class template specialization
template<>
class solve<IPOPT>
{
...
The proper syntax for that should not mention template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
You should remove template<>, i.e.
// template <>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
template<> is used for template specialization (for a template); but you're just defining a non-template member function (of a class template specialization). (That's why the compiler complains that the template declaration can't be found.)

Is it legal to perform partial in-class specialization of a member template class in derived class

It is continuation of this question. I am specifically interested if the partial specialization of a member class like this:
struct FooParent {
template <class>
struct Bar{ };
};
struct Foo: FooParent {
template <class T>
struct Bar<T*> {};
};
I know this can be done inside a namespace scope:
template <class T>
struct Foo::Bar<T*>{ };
But I'm also specifically interested in in-class partial specialization at the level of derived class.
Both clang and gcc complains when encounter a former:
clang states that there is an explicit template specialization which obviously does not occur:
error: explicit specialization of 'Bar' in class scope
gcc is a little bit less verbose here and says that the specialization of the member template must be performed at a namespace scope which obviously is not a case for not derived class.
error: specialization of 'template struct FooParent::Bar' must appear at namespace scope
Is gcc right here in his error message?
I'm trying to sum up what I said in the comments to the question, as requested by the OP.
I guess [temp.class.spec]/5 is enough to reply to the question.
In particular:
A class template partial specialization may be declared or redeclared in any namespace scope in which the corresponding primary template may be defined [...].
In this case, what actually rule on it is where the primary template can be defined.
In the example, you are trying to declare (and contextually define, but it's first of all a declaration) a partial specialization in a derived class.
The short answer is: you cannot define the primary template in the derived class, so you cannot declare a partial specialization in that class as well.
If it was possible , the following would have been possible too:
struct FooParent {
template <class>
struct Bar;
};
struct Foo: FooParent {
template <class T>
struct FooParent::Bar<T*> {};
};
Or this one if you prefer:
struct Foo: FooParent {
template <class T>
struct Bar<T*> {};
};
Unfortunately (?) they are not allowed and this would suffice to tell you that your attempt to specialize the class template is invalid as well.
Anyway, let's consider it a bit further.
The primary template is part of the member specification of Foo (see here for further details).
Thus, the question - where can I define such a template?, quickly becomes - where can I define any other member of the class?.
Again, the answer is - not in the scope of a derived class.
I'm pretty sure that a language-lawyer would give you more direct and straightforward explanation.
I'm also pretty sure that the same language-lawyer would curse me for having mentioned the wrong sections of the standard.
Anyway, I hope the few examples above can give you a base point from which to start.

C++ Inheriting from Undefined Template Type

This code:
template <class T>
class Foo {};
typedef Foo<void*> Bar;
template <class T>
class Foo<T*> : public Bar {};
// use Foo<int*> somewhere.
Compiles and works fine in MSVC 9.0, but doesn't compile in GCC 4.1.1 or GCC 4.3.4, with the error:
error: invalid use of undefined type 'class Bar'
Is this illegal C++ that MSVC accepts incorrectly, or a limitation of GCC?
Either way, how can I work around this get the desired behaviour: pointer specialisations of Foo that inherit from unspecialised Foo<void*>?
You cannot do that, except by writing the specialization for all T*, except when T is void. Otherwise, you will derive the class from itself, which for obvious reasons can't work.
Instantiating the primary class template for arguments that have an explicit or partial specialization is not possible. If you try to, by provoking an instantiation before the explicit or partial specialization is visible (note that your code did not provoke such an instantiation), your program is ill-formed, with no diagnostic being required (which effectively renders the behavior undefined).
To achieve the above work-around, you can use SFINAE
template <class T>
struct isnt_void { typedef void type; };
template<> struct isnt_void<void> { };
template <class T, class = void>
class Foo {};
template <class T>
class Foo<T*, typename isnt_void<T>::type> : public Foo<void*> {};
The typedef is a red herring.
The following code is equivalent:
template <class T>
class Foo {};
template <class T>
class Foo<T*> : public Foo<void*> {};
It should be clear that, although Foo<T*> is declared at this point, it is not defined. And thus you may not use it as a base.
[class.name] (2003 wording, 9.1/2):
A class definition introduces the class name into the scope where it is defined
[class.mem] (2003 wording, 9.2/2):
A class is considered a
completely-defined object type (3.9)
(or complete type) at the closing } of
the class-specifier. Within the class
member-specification, the class is
regarded as complete within function
bodies, default arguments and
constructor ctor-initializers
(including such things in nested
classes). Otherwise it is regarded as
incomplete within its own class
member-specification.
[class.derived] (2003 wording, 10/1):
The class-name in a base-specifier shall not be an incompletely defined class (clause 9);
A superior solution would be to compose of Foo<void*>. After all, you don't want the raw void* interface cluttering up your stuff, and you don't want a Foo<T*> to be convertible to a Foo<void*>.
Alternatively, you could fully specialize Foo<void*> beforehand.
Assuming, of course, that you're doing this for type folding, instead of because you actually want inheritance.

Specialization of member class nested in a non-specialized class

template <typename T>
struct A
{
template <typename U>
struct B;
template <>
struct B<int> {static const int tag = 1;}; // Works fine in VS2010
};
How can I specialize B the same way, but outside of A. I tried this with no success :
template <typename T> template <>
struct A<T>::B<int> {static const int tag = 1;};
I get:
error C3212: 'A<T>::B<int>' : an explicit specialization of a template member must be a member of an explicit specialization
It does not make sense since I can do exactly that by defining it inside the class
VS2010 problem? Wrong syntax?
Thanks
PS: This one (which should be wrong anyway, crashes VS2010):
template <> template <typename T>
struct A<T>::B<int> {static const int tag = 1;};
To quote the C++ spec, ยง14.17.3.18:
In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialzed, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well. [...]
(my emphasis)
This suggests that you can't specialize a template class nested inside another template class unless the outer template class is specialized as well. So it looks like VS2010 has this behavior wrong and g++ has it right.
It just doesn't work that way.:-(
You cannot specialize a function inside the class declaration, even though msvc accepts this with its default settings.
You also cannot specialize a member function without also specializing the enclosing class. Most compilers avred on this (as does the language standard).