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 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.
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.
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.
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.
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>
// ^^^^^^^^^^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With