简体   繁体   中英

C++ template specialization and function returned value

How would I specialize the getValue() function in the following example to return a value based on a type? How to achieve this in the class definition? Is it possible?

template <typename Type>
class Abc
{
    public:
        Type init;
        Abc() : init(getValue()) {}
    private:
        template<> static uint8_t getValue() { return 123; }
        template<> static uint16_t getValue() { return 45678; }
};

You can use std::is_same to write a non-templated function that returns a value depending on the template parameter of the class:

template <typename Type>
class Abc
{
    ...
    static Type getValue() { 
        if (std::is_same<Type, std::uint8_t>::value) {
            return 123;
        } else if (std::is_same<Type, std::uint16_t>::value) {
            return 45678;
        }
    }
};

This example is simple enough that this will compile with C++11: both return statements are valid regardless of whether Type is a uint8_t or a uint16_t . However, if it gets more complicated you might have to use C++17's constexpr if , for example:

    static Type getValue() { 
        if constexpr (std::is_same<Type, std::uint8_t>::value) {
            return 123;
        } else if constexpr (std::is_same<Type, std::uint16_t>::value) {
            return 45678;
        } else if constexpr (std::is_same<Type, const char *>::value) {
            return "9abcdef";
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM