Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alias a static template method?

Tags:

c++

c++11

I have the following class:

struct A
{
    template<typename T1, typename T2>
    static double constexpr getPercentage(const T1 t1, const T2 t2)
    {
        return 100.0 * static_cast<double>(t1) / static_cast<double>(t2);
    }
};

I have aliased and use A::getPercentage for B as follows:

struct B
{
    template<typename T1, typename T2>
    using getPercentage = decltype(A::getPercentage<T1, T2>);

    void f()
    {
        const double d = getPercentage(1.0, 2.0); //ERROR: Cannot refer to class template 'getPercentage' without a template argument list
    }
};

What is wrong with this? How can I avoid this error?

like image 947
Vahagn Avatar asked Apr 20 '26 11:04

Vahagn


1 Answers

The using is a type alias. getPercentage is not a type, it is a function. You cannot alias functions.

Form what your intent looks like, a forwarding function would be more appropriate.

template <typename T1, typename T2>
double constexpr getPercentage(T1&& t1, T2&& t2)
{
    return A::getPercentage(std::forward<T1>(t1), std::forward<T2>(t2));
}

For a full listing;

struct A
{
    template<typename T1, typename T2>
    static double constexpr getPercentage(const T1 t1, const T2 t2)
    {
        return 100.0 * static_cast<double>(t1) / static_cast<double>(t2);
    }
};

struct B
{
    template <typename T1, typename T2>
    static constexpr double getPercentage(T1&& t1, T2&& t2)
    {
        return A::getPercentage(std::forward<T1>(t1), std::forward<T2>(t2));
    }

    void f()
    {
        const double d = getPercentage(1.0, 2.0);
    }
};
like image 80
Niall Avatar answered Apr 23 '26 00:04

Niall