Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template with default value of method pointer argument

Consider this special container class that stores types that contain both key and value inside it, so

template<typename K, typename T, K (T::*method)() const>
class Container
{
//...
};

K is the type of a key, T is a type of value and the method pointer is used to retreive the key from the value.

It works fine but I would like to include a default for the method pointer so that when it was not specified by the caller it would be operator K() const like so:

template<typename K, typename T, K (T::*method)() const = &T::operator K const>

but this does not compile stating there is no member operator const K on A (<- my class I test this with) when I try to instantiate it (and there is such a method). Is it even possible to have default value of a method pointer template argument? If yes, what is the correct syntax?

EDIT: In addition to the solution below there is a "fix" for the cases when T is a pointer that uses new C++11 feature std::remove_pointer<T>::type, so:

template<typename K, typename T, K (std::remove_pointer<T>::type::*method)() const = &std::remove_pointer<T>::type::operator K>
like image 684
Resurrection Avatar asked Dec 16 '15 16:12

Resurrection


People also ask

Can we specify default value for template arguments?

Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.

What is a template argument in C++?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How do I restrict a template type in C ++?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

What is a template parameter?

In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.


1 Answers

The name of the function is just operator K. Its qualification isn't part of the name. Try:

template <typename K,
          typename T,
          K (T::*method)() const = &T::operator K>
//                                 ^^^^^^^^^^^^^^
like image 195
Kerrek SB Avatar answered Sep 22 '22 00:09

Kerrek SB