void myfunc(Iterator a...">

C ++ - typedef "inside" template arguments?

Imagine that I have a template function like this:

template<typename Iterator> void myfunc(Iterator a, typename Iterator::value_type b) { ... } 

Is there a way to implement the same thing by declaring a typedef for Iterator :: valuetype that I can use in a function signature? For example, I would rather do something like this:

 template< typename Iterator, typedef Iterator::value_type type> void myfunc(Iterator a, type b) { ... } 

So far, I have resorted to using the default template arguments and checking the Boost concept to ensure that the default value is always used:

 template< typename Iterator, typename type = typename Iterator::value_type > void myfunc(Iterator a, type b) { BOOST_STATIC_ASSERT(( boost::is_same< typename Iterator::value_type, type >::value )); ... } 

... but it would be nice if there was support in this language.

Edit

I probably should have used a class instead of a function, since the default arguments are not standard for functions.

 template< typename T, typename V = typename T::value_type> class A : public B<T, V> { BOOST_STATIC_ASSERT((boost::is_same<typename T::value_Type, V>::type)); }; 
+4
source share
2 answers

You are looking for a template typedef for use in defining template functions. I don’t think you can do this ...

You may have a template class with a static function and typedefs ... But using it gets ugly:

 template<typename Iterator> class arbitraryname { public: typedef typename Iterator::value_type value; static void myfunc( Iterator a, value b ) { value c = b; cout << "Test" << c << endl; } }; struct Foo { typedef int value_type; }; int main() { Foo f; myfunc<Foo>(f,2); // Old way. arbitraryname<Foo>::myfunc(f,3); // With templated class. } 

Personally, in this case, I would go with #define ...

 #define VALUE_TYPE typename Iterator::value_type template<typename Iterator> void myfunc(Iterator a, VALUE_TYPE b) #undef VALUE_TYPE { typedef typename Iterator::value_type bar; bar z = b; cout << "Test" << z << endl; } 

Of course, #define are ugly and sinful. But also a code that is painfully stupid to read ...

ps To be safe, you can add:

 #ifdef VALUE_TYPE #error "VALUE_TYPE already defined!" #endif 
+2
source

You can use typename in the parameter list:

 template <typename Iterator> void myfunc(Iterator a, typename Iterator::value_type b) { } 
+2
source

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


All Articles