Specify behavior of a class member function based on type passed C++

5vf7fwbs  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(127)

A simplified example of my code:

namespace Example 
{
    class A
    {
    public:

        template<typename T>
        void foo(T &val);

        template<>
        void foo<long>(long &val);
    };

    template<typename T>
    void A::foo(T &val) 
    {
        std::cout << "Generic Function: " << val << std::endl;
    }

    template<>
    void A::foo<long>(long &val)
    {
        std::cout << "Specialized Function: " << val << std::endl;
    }
}

I get an error like:
explicit specialization in non-namespace scope
Why doesn't template specialization work here? How can I specify the behavior of a member function based on the type that's passed in?

sc4hvdpw

sc4hvdpw1#

You don't need specialization for this, simple overloading will work fine (ie, remove the template<> from the 2nd foo() ), eg:

namespace Example 
{
    class A
    {
    public:

        template<typename T>
        void foo(T &val);

        void foo(long &val);
    };

    template<typename T>
    void A::foo(T &val) 
    {
        std::cout << "Generic Function: " << val << std::endl;
    }

    void A::foo(long &val)
    {
        std::cout << "Specialized Function: " << val << std::endl;
    }
}

Online Demo
Or, in C++17 and later, you can just get rid of the 2nd foo() altogether and use if constexpr inside the implementation of the 1st foo() , eg:

#include <type_traits>

namespace Example 
{
    class A
    {
    public:

        template<typename T>
        void foo(T &val);
    };

    template<typename T>
    void A::foo(T &val) 
    {
        if constexpr (std::is_same_v<T, long>)
            std::cout << "Specialized Function: " << val << std::endl;
        else
            std::cout << "Generic Function: " << val << std::endl;
    }
}

Online Demo

相关问题