Portable "type" name with external connection

Article Dr.Dobb Portable operator "typeof" said

But you cannot use a class template to extract a type from an expression, as you can with function templates or overloading. (If the expression is an external link name, you can implement typeof using class templates using a template parameter that is not a type, but this is not very useful.)

Is the bold sentence in parentheses correctly highlighted? And if so, how can I use the template non-peak parameter to find the type of expression with external connection?

+5
source share
2 answers

In C ++ 03, there is no way to implement typeof without using sizeof . The closest useful alternative is to extract the type using a function template that returns the desired type.

 template<typename T> struct Type { }; template<typename T> Type<T> makeType(T) { return Type<T>(); } int main() { int i; makeType(2 + 2); // Type<int> makeType(&i); // Type<int*> } 

The following method uses function templates in C ++ 03 to extract the type and value of any expression that can be used in a template argument.

 template<typename T, T value> struct NonType { }; template<typename T> struct Type { template<T value> static NonType<T, value> makeNonType() { return NonType<T, value>(); } }; template<typename T> Type<T> makeType(T) { return Type<T>(); } #define MAKE_NONTYPE(e) makeType(e).makeNonType<e>() int i; int main() { MAKE_NONTYPE(2 + 2); // NonType<int, 4> MAKE_NONTYPE(&i); // NonType<int*, i> } 

The following answer shows the practical use of this method to extract the type and value of a pointer to an expression of a member function: How to enable the functor template to work for both member functions and non-members

+2
source

This does not work in C ++ 03 - the approach is actually pointless, I believe the author did not quite understand this idea.

However, with implicit template parameters (as suggested for C ++ 1Z), this can really work:

 template <using typename T, T&> struct infer {using type = T;}; int a; infer<a>::type // int 

It still does not determine if a is a reference.

+2
source

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


All Articles