Search code examples
c++templatespointer-to-membertemplate-argument-deduction

Allow for template argument deduction of type of member pointed to by pointer to member argument of method


I have made the following method as a little experiment to find out if this would be possible:

template<typename dataT>
class DemographicNode
{
    //...
    template<typename varT>
    varT count(const varT dataT::* variable = &dataT::citizens) const {
        //...
    }
    //...
}

This works as expected except for the fact that this doesn't allow for template argument deduction of varT even though a call to this method would provide all the compile-time available information required.

Is there any way to enable template argument deduction in this case?

I am using VC++17.

Edit: I have to call it in the following way:

gameState.getCountries()[0]->getDemoGraphics().count<double>();

and I want to call it with something like this:

gameState.getCountries()[0]->getDemoGraphics().count();

Solution

  • As mentioned in the comments, template argument deduction does not work with default arguments.

    Here you can simply set a default template parameter for varT:

    template<typename varT = decltype(dataT::citizens)>
    varT count(const varT dataT::* variable = &dataT::citizens) const {
    
    };
    

    Or you can add an overload without parameters for count():

    template<typename dataT>
    class DemographicNode {
    public:
        // no more default argument here
        template<typename varT>
        varT count(const varT dataT::* variable) const {
        };
    
        // overload without parameters
        auto count() const {
            return count(&dataT::citizens);
        }
    };