C ++ template parameter and partial specialization: strong or weak typing?

Today, my friend and I struggled a lot with a stupid mistake, and I make you think about how the template parameters work in C ++. Consider the following code, where I am trying to partially specialize the class attr<MyClass<I>> , where I is an unsigned int , although MyClass expects an int parameter:

 #include <iostream> template<int I> class MyClass { }; template<typename T> struct attr; template<unsigned int I> struct attr<MyClass<I>> { }; int main(int argc, char *argv[]) { attr<MyClass<1>> att; return 0; } 

g++ comes out with an error message

 main.cpp: In function 'int main(int, char**)': main.cpp:20:22: erreur : aggregate 'attr<MyClass<1> > att' has incomplete type and cannot be defined attr<MyClass<1>> att; 

And clang compiles it (only a warning because att not used).

Therefore, I was wondering:

  • is there anything in the specification that will rule in favor of one or the other?

  • can we say that the clang set of template parameters is weaker than g++ ?

+5
source share
1 answer

Yes, the GCC correctly rejects, at least according to current standards. Perhaps the Clang people presented some kind of defect report here, I would not know.

http://eel.is/c++draft/temp.deduct.type#17

If P has a form containing <i> , and if the type of the corresponding value of A is different from type i, then the output is not performed. If P has a form containing [i] , and if type i is not an integral type, then inference is not performed.

Their test test at testuite only checks this for functions for which they seem to be emitting reasonable error messages: https://github.com/llvm-mirror/clang/blob/master/test/CXX/temp/temp.fct .spec / temp.deduct / temp.deduct.type / p17.cpp .

In addition, since incomplete specialization can never be inferred, we also come across http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#549 , which asks if such constructs should be rejected to the front. In my opinion, http://eel.is/c++draft/temp.res#8 can be applied if you want:

"Knowing which names are type names, you can check the syntax of each template. The program is unformatted, diagnostics are not required if:

  • a valid specialization cannot be created for the template, and this template is not created, or ... "

There is no legal way to run an instance of this template, so you can argue that no valid specialization can be created for it. According to this interpretation, the behavior is undefined and it is legal to do something.

+1
source

Source: https://habr.com/ru/post/1244829/


All Articles