简体   繁体   English

C++ 模板特化和函数返回值

[英]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?在以下示例中,我将如何专门化 getValue() 函数以返回基于类型的值? 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:您可以使用std::is_same编写一个非模板化函数,该函数根据类的模板参数返回一个值:

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 .这个例子很简单,可以用 C++11 编译:无论Typeuint8_t还是uint16_t ,这两个return语句都是有效的。 However, if it gets more complicated you might have to use C++17's constexpr if , for example:但是,如果它变得更复杂,您可能必须使用 C++17 的constexpr if ,例如:

    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";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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