Recently I started to use template.
And I just dump in a compile error.
I have a Class Template Foo which take a boolean B as a template parameter.
And I'm trying to make friend, in an instentiation of Foo with template argument b, the Constructor of the other instantiation of Foo with argument !b with this code:
template<bool B>
class Foo
{
public:
Foo(Foo<!B>&);
private:
friend Foo<!B>::Foo(Foo<B>&);
};
The compiler return me these errors:
test.cpp:22:18: error: C++ requires a type specifier for all declarations
friend Foo<!B>::Foo(Foo<B>&);
~~~~~~ ^
test.cpp:22:18: error: constructor cannot have a return type
friend Foo<!B>::Foo(Foo<B>&);
^~~
2 errors generated.
I compiled it with the following command: clang++ -std=c++11 foo.cpp on Windows.
I really don't understand how to make it work, any help to understand what's wrong is appreciated.
I was commenting on someone else's answer and they asked me to paste my analysis here.
I think that your case is problematic because Foo<true> has a friend declaration to Foo<false>'s member function which in turn refers to Foo<true>'s member function. While the members respectively are declared before the member functions, this kind of circular reference is not supported by compilers. GCC complains at instantiation
main.cpp: In instantiation of 'class Foo<false>':
main.cpp:9:12: required from 'class Foo<true>'
main.cpp:15:49: required from here
main.cpp:9:12: error: invalid use of incomplete type 'class Foo<true>'
friend Foo<!B>::Foo(Foo<B>&);
This error message is a bit confusing, because it suggests that incomplete types could not be used with ::, which is wrong. A class that is being defined can be used with :: even if it is incomplete yet. A class however that is being instantiated is handled differently by GCC than a class that is being defined, and refering back to the class that is being instantiated in a qualified name is not supported by GCC apparently.
We have a DR about such cyclic references, http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#287 which would appear to make this legal, but as the final statement notes, "This needs work", so GCC is in its right to reject your code I would say. To add to that confusion, we also have an explicit rule for names used in friend function declarations, which isn't mentioned in DR287 and its "as if" would make your code ill-formed because Foo<!B>'s point of instantiation is immediately before the point of instantiation of Foo<B> and unless we apply the rule in DR287 cannot see the constructor declaration of Foo<B>.
Friend classes or functions can be declared within a class template. When a template is instantiated, the names of its friends are treated as if the specialization had been explicitly declared at its point of instantiation
Independent of this, there's another issue at hand: Is Foo<!B>::Foo(Foo<B>&); referring to a constructor? It is a reference to the constructor if it refers to the injected class name, which the compiler then must treat as the constructor in these constexts. So the compiler must resolve Foo<!B>::Foo. But Foo<!B> is a dependent type, so the compiler cannot look into it to decide what kind of name it is (remember that struct A { int A; } is allowed, and the compiler has to verify it is not in such a situation). I think for these reasons, cland fails to parse your template because it is confused as to what friend Foo<!B>::Foo(Foo<B>&) means.
I believe the template itself (disregarding issues of instantiation) should be well-formed because the compiler could just delay the lookup of Foo<!B>::Foo and take it as a non-type which it actually is (constructors).
Related
The question of implementing a template friend function inside a template class was already discussed in the past and seem to be an unresolved issue in the standard with different behavior of the different compilers.
Checking newest available versions of gcc and clang it seems that the decision is taken, to require the implementation of template friend function to be outside of the template class.
The following code is rejected by newest versions of both gcc and clang (gcc x86-64 9.2.0 and clang x86-64 9.0.0) when compiled with -std=c++2a. Past versions of clang are ok with it (e.g. clang x86-64 7.0.0).
template<long Num>
struct A {
template<long Num1, long Num2>
friend int foo(A<Num1> a1, A<Num2> a2) {
return 1;
}
// the compilation error occurs only with a template friend function
// and only if *implemented inside* a template class
};
int main() {
A<1> a1;
A<2> a2; // commenting this line removes the error
}
Both compilers complain on redefinition of foo:
<source>:4:16: error: redefinition of 'foo'
friend int foo(A<Num1> a1, A<Num2> a2) {
^
<source>:11:10: note: in instantiation of template class 'A<2>' requested here
A<2> a2;
^
Is there a new official resolution on the subject or is it just the latest compilers fashion?
https://godbolt.org/z/ySrVe3
I figured out the relevant wording from the resolution of CWG 2174. It is in [temp.inst]/2 in C++17:
However, for the purpose of determining whether an instantiated redeclaration is valid according to [basic.def.odr] and [class.mem], a declaration that corresponds to a definition in the template is considered to be a definition.
Thus, the compiler is required to defer the actual instantiation of the definition until the point where a definition of foo is required to exist (in your code, there is no such point, so foo is not instantiated), but even if the definition is not instantiated, the compiler is still required to diagnose multiple definitions within the same translation unit as if the definition had been instantiated every time the declaration were instantiated.
It seems to me that this rule makes it unnecessarily difficult to use friend functions for no obvious benefit, and that it would be better if multiple definitions of a friend function defined inside a class template, instantiated within the same TU, were considered as a single definition. Perhaps, if I had more time on my hands, I would propose making such a change to the standard. (Yes, I am saying I don't have the time, so if anyone else wants to do this, please go ahead without worrying about duplicated effort.)
Unless such a change is made, it seems that you do, in fact, need to define the friend function outside the class template.
I am trying to understand the following code snippets
Snippet #1
template <typename T>
struct A
{
static constexpr int VB = T::VD;
};
struct B : A<B>
{
};
Neither gcc9 nor clang9 throw an error here.
Q. Why does this code compile? Aren't we instantiating A<B> when inheriting from B? There is no VD in B, so shouldn't the compiler throw an error here?
Snippet #2
template <typename T>
struct A
{
static constexpr auto AB = T::AD; // <- No member named AD in B
};
struct B : A<B>
{
static constexpr auto AD = 0xD;
};
In this case, gcc9 compiles fine but clang9 throws an error saying "No member named AD in B".
Q. Why does it compile with gcc9/why doesn't it compile with clang9?
Snippet #3
template <typename T>
struct A
{
using TB = typename T::TD;
};
struct B : A<B>
{
using TD = int;
};
Here both clang9 and gcc9 throw an error. gcc9 says "invalid use of incomplete type 'struct B'".
Q. If struct B is incomplete here then why is it not incomplete in snippet #2?
Compiler flags used: -std=c++17 -O3 -Wall -Werror. Thanks in Advance!!!
I believe these essentially boil down to [temp.inst]/2 (emphasis mine):
The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions, default arguments, or noexcept-specifiers of the class member functions, member classes, scoped member enumerations, static data members, member templates, and friends; […]
and [temp.inst]/9
An implementation shall not implicitly instantiate […] a static data member of a class template […] unless such instantiation is required.
The wording in the standard concerning implicit template instantiation leaves many details open to interpretation. In general, it would seem to me that you simply cannot rely on parts of a template not being instantiated unless the specification explicitly says so. Thus:
Snippet #1
Q. Why does this code compile? Aren't we instantiating A when inheriting from B? There is no VD in B, so shouldn't the compiler throw an error here?
You are instantiating A<B>. But instantiating A<B> only instantiates the declarations, not the definitions of its static data members. VB is never used in a way that would require a definition to exist. The compiler should accept this code.
Snippet #2
Q. Why does it compile with gcc9/why doesn't it compile with clang9?
As pointed out by Jarod42, the declaration of AB contains a placeholder type. It would seem to me that the wording of the standard is not really clear on what is supposed to happen here. Does the instantiation of the declaration of a static data member that contains a placeholder type trigger placeholder type deduction and, thus, constitute a use that requires the definition of the static data member? I can't find wording in the standard that would clearly say either yes or no to that. Thus, I would say that both interpretations are equally valid here and, thus, GCC and clang are both right…
Snippet #3
Q. If struct B is incomplete here then why is it not incomplete in snippet #2?
A class type is only complete at the point where you reach the closing } of the class-specifier [class.mem]/6. Thus, B is incomplete during the implicit instantiation of A<B> in all your snippets. It's just that this was irrelevant for Snippet #1. In Snippet #2, clang did give you an error No member named AD in B as a result. Similar to the case of Snippet #2, I can't find wording on when exactly member alias declarations would be instantiated. However, unlike for the definition of static data members, there is no wording in place to explicitly prevent the instantiation of member alias declarations during implicit instantiation of a class template. Thus, I would say that the behavior of both GCC and clang is a valid interpretation of the standard in this case…
I wrote a singleton template class just like boost does:
template <typename _T>
class Singleton
{
public :
static _T* Instance()
{
static _T obj;
return &obj;
}
protected :
Singleton() {}
private :
struct ObjectCreator
{
ObjectCreator()
{
Singleton<_T>::instance();
}
};
static ObjectCreator object_creator;
};
template <typename _T>
typename Singleton<_T>::ObjectCreator Singleton<_T>::object_creator;
And I wrote the main function to test it.
#include "Singleton.h"
class A : public Singleton <A>
{
public:
int a;
};
int main()
{
A::Instance()->a = 2;
}
I know I mistyped Instance in ObjectCreator's constructor, the weird thing is I can compile it correctly by gcc-4.4.7, then I used clang-6.0, it hit me with the typo.
I guess gcc can do some optimization, because I did not do anything with ObjectCreator, so it ignored the error code.
I have two questions:
What should I do to make gcc report me that error (without changing my code), like add some compiler flag?
If anyone has a more reliable explanation for this? Some official doc would do.
Ps: I am aware that boost would add a do_nothing function in ObjectCreate and call it from Singleton<_T>:: Instance() to avoid this optimization.
What should I do to make gcc report that error (without changing my code), like add some compiler flag?
You could add an explicit instantiation template class Singleton<float>; (I just randomly picked float as type, but you could choose anything more appropriate) to force GCC to check for syntax. See https://gcc.godbolt.org/z/ii43qX for an example.
If you simply want the check, you could also put this explicit instanciation to a separate compilation unit by adding another cpp-file to your project.
However, doing an explicit instanciation is stronger than the implicit instanciation, as all members and methods are going to be instanciated. This behavior might be anwanted (see standard library for examples).
If anyone has a more reliable explanation for this? Some official doc would do.
Static members are not initialized implicitly until it is used in a way that its definition is required (this is very different to the explicit instanciation).
#StoryTeller found the right paragraph in the standard
14.7.1 Implicit instantiation [temp.inst]
The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates; and it causes the implicit instantiation of the definitions of member anonymous unions. Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
EDIT
You should accept the answer of #StoryTeller as he correctly explained both aspects of your question first.
If I read the standard correctly, I don't believe your code is ill-formed (bar the use of a _T identifier). Clang going the extra mile is fantastic, but GCC isn't wrong to accept it as is.
The reason is your program only contains an implicit instantiation of your template. According to N19051 (emphasis mine):
14.7.1 Implicit instantiation [temp.inst]
1 ... The implicit instantiation of a class
template specialization causes the implicit instantiation of the
declarations, but not of the definitions or default arguments, of the
class member functions, member classes, static data members and member
templates; and it causes the implicit instantiation of the definitions
of member anonymous unions. Unless a member of a class template or a
member template has been explicitly instantiated or explicitly
specialized, the specialization of the member is implicitly
instantiated when the specialization is referenced in a context that
requires the member definition to exist; in particular, the
initialization (and any associated side-effects) of a static data
member does not occur unless the static data member is itself used in
a way that requires the definition of the static data member to exist.
Nothing uses object_creator in a way that requires its definition to exist. As such only the declaration is ever checked. Furthermore, only the declaration of class ObjectCreator is required to be instantiated itself, not its definition (or the definition of its constructor). This is for the same reason one can define an extern variable of a forward declared class type:
extern class C c;
The above paragraph (and the fact nothing uses object_creator) only requires the type name and object name be instantiated, to produce an effect similar to the above external declaration.
As a result GCC never has to verify instance is valid. I would say that given the above paragraph, even if you didn't have a typo, it's quite possible object_creator doesn't do what you think it does. If your code worked, it's only because the function local static obj was initialized on first use (making ObjectCreator redundant).
As for why adding an explicit instantiation (like #P i suggested) immediately causes an error. We can see here:
14.7.2 Explicit instantiation [temp.explicit]
7 The explicit instantiation of a class template
specialization also explicitly instantiates each of its members (not
including members inherited from base classes) whose definition is
visible at the point of instantiation and that has not been previously
explicitly specialized in the translation unit containing the explicit
instantiation.
When we do that, we recursively force everything to be instantiated, and as a result, checked.
1 - This is a 2005 draft. Very close to C++03, and therefore I believe appropriate given your use of GCC 4.4.7.
Consider the following example:
template <class T>
class C
{
public:
C();
C(C&& rhs);
private:
T m_data;
};
template <class T>
C<T>::C()
: m_data(T())
{
}
template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
}
int main()
{
C<int> i;
}
Line : m_data(rhs.data) contains an error as C does not have a member named data. But none of the compilers that I tried (gcc 5.2, clang 3.5.1) detected that error.
But when I add the following line to main function the compiler detects the error:
C<int> j = std::move(i);
Why the compiler does not give an error in the first case?
Even if that particular function is not called it can figure out that C has no member named data.
In addition when I change the definition of move constructor to the following:
template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
data = 0;
}
the compiler gives error on line data = 0; but not on : m_data(rhs.data).
So the function gets parsed.
There is 2 passes to check error in template.
One for non dependent code
One for dependent code (done at instantiation)
Your code is template dependent, so it is checked only when the method is instantiated.
Your template is ill-formed but the error does not require a diagnostic (in other words, the compiler is allowed to not give an error message and can do anything it wants). More precisely, the Standard says
Similarly, if the id-expression in a class member access expression for which the type of the object expression is the current instantiation does not refer to a member of the current instantiation or a member of an unknown specialization, the program is ill-formed even if the template containing the member access expression is not instantiated; no diagnostic required.
In your code C is the current instantiation and rhs.data is a class member access expression but does not refer to a member of the current instantiation and not to a member of an unknown specialization (which would be the case if C had dependent base classes, i.e if you would have written class C : T or something similar).
To read up on these rules, see this answer . It is also worth nothing that this kind of code has always been ill-formed (no diagnostic required), even in C++03 that didn't have this addition rule that I quoted. Because this code makes the template have no valid instantiation, for all possible types of T. But the existing rule of C++03 is rather broad and this addition of C++11 is a succinct test that allows this kind of code to be safely rejected.
the compiler does not try to compile C(C&& rhs); since you don't call it (in the first try).
this is called the zero overhead rule in C++ - you don't pay on what you don't use.
when you try to call it the compiler than tries to compile the function and fails.
In this case, the compiler obiously couldn't figure out that the move constructor will never work. It is allowed to do so, but not required.
In the general case, it is hard to detect that there is no T whatsoever for which the code could be compiled. If it just fails for C<int> and C<float>, but works for C<my_class>, the compiler must not complain (as long as the function isn't used for int or float).
The following code compiles on GCC (doesn't even require a recent version), but it fails on clang 3.4:
template <int N>
struct T_unsigned {
typedef typename T_unsigned<N>::Type Type;
};
template <> struct T_unsigned<8> {
typedef unsigned char Type;
};
Using the above definition of T_unsigned, GCC allows you to use "T_unsigned<8>::Type" instead of "unsigned char". When I try to compile this using clang 3.4, I get:
test.cpp:3:41: error: no type named 'Type' in 'T_unsigned<N>'
typedef typename T_unsigned<N>::Type Type;
~~~~~~~~~~~~~~~~~~~~~~~~^~~~
1 error generated.
Is clang failing to compile correct C++11 code, or is this code doing something non-standard that GCC happens to support?
In your general case T_unsigned<N>, we have:
A name is a member of the current instantiation if it is
[...]
A qualified-id in which the nested-name-specifier refers to the current instantiation.
[ Example:
template <class T> class A {
static const int i = 5;
int n1[i]; // i refers to a member of the current instantiation
int n2[A::i]; // A::i refers to a member of the current instantiation
int n3[A<T>::i]; // A<T>::i refers to a member of the current instantiation
int f();
};
Within T_unsigned<N>, T_unsigned<N> is just another name for itself. So basically you have something like:
class Foo {
typedef Foo::Type Type;
};
and the "correct" error message should be approximately (http://ideone.com/FvJHBF):
prog.cpp:2:17: error: ‘Type’ in ‘class Foo’ does not name a type
typedef Foo::Type Type;
^
However, you write that you have problems with using your specialization T_unsigned<8>, which is seemingly not found by clang.
Your testcase is not too exhaustive, so my answer depends on an if-statement:
If at the point of instantiation, your specialization for N=8 is visible, than clang is doubly wrong. If not, gcc and clang should both fail, but with aforementioned error message (though the error message itself is in no way defined by the standard, so this is a tool's should, not a standard's).
The name that you use as the typedef is not dependent (see the clauses that define dependent names) and the namelookup in definition context at that place will not find a declaration. That in itself is an error already.
But since there is no declaration for the name yet, the name is also not a member of a class that is the current instantiation or a base class thereof. Therefore the name is not a member of the current instantiation and therefore we have another reason to reject it by a rule that says that if the qualifier is the current instantiation, the name either must refer to a member of that instantiation, or to a member of an unknown specialization (which would be the case if the class had dependent base classes).
Note the notion of "current instantiation": the meaning of the qualifier is fixed to refer to the result of instantiating the surrounding template, we don't wait for resolving the template arguments. Hence the term is not called "current specialization", since we know that it refers to an instantiated specialization, as opposed to a later declared explicit specialization.
The thing is different for C++03 I think. The name will be dependent and the template definition is harder to deem illformed with the rules available. The illformed, no diagnostic required, behavior will however happen when you try to instantiate the template before providing the explicit specialization. I think such code refering to itself makes no sense because you never are able to actually instantiate the template validly (and there is a rule that allows rejecting a template straight away in such cases).