Kyle Simek
Kyle Simek

Reputation: 9636

C++ -- typedef "inside" template arguments?

Imagine 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 declare a typedef for Iterator::valuetype that I can use in the function signature? For example, I'd prefer to be able to do something like this:

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

Thus far, I've resorted to using default template arguments and Boost concept checking to ensure the default 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 the language for this type of thing.

Edit

I probably should have used a class instead of a function, since default arguments aren't 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));
};

Upvotes: 5

Views: 5400

Answers (2)

Mr.Ree
Mr.Ree

Reputation: 8418

You are looking for a templated typedef to be used inside a templated function definition. I don't think you can do that...

You can have a templated class with a static function & 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'd go with a #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;
}

Sure #define's are ugly and sinful. But so is code that's painfully obtuse to read...

p.s. Just to be safe, you might want to add:

#ifdef  VALUE_TYPE
#error "VALUE_TYPE already defined!"
#endif

Upvotes: 2

James McNellis
James McNellis

Reputation: 355039

You can use typename in the parameter list:

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

Upvotes: 2

Related Questions