Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板专门化和函数返回值_C++_Templates_Template Specialization - Fatal编程技术网

C++ C++;模板专门化和函数返回值

C++ C++;模板专门化和函数返回值,c++,templates,template-specialization,C++,Templates,Template Specialization,在下面的示例中,如何专门化getValue()函数以返回基于类型的值?如何在类定义中实现这一点?可能吗 template <typename Type> class Abc { public: Type init; Abc() : init(getValue()) {} private: template<> static uint8_t getValue() { return 123; }

在下面的示例中,如何专门化getValue()函数以返回基于类型的值?如何在类定义中实现这一点?可能吗

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; }
};
模板
Abc班
{
公众:
init型;
Abc():init(getValue()){}
私人:
模板静态uint8_t getValue(){return 123;}
模板静态uint16_t getValue(){return 45678;}
};
您可以使用编写非模板函数,该函数根据类的模板参数返回值:

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

当然可以,但它超出了类定义。内部也可以这样做吗?您可以添加一个小的
main
函数,使用
Abc
并描述您想要的行为吗?@noonespecial这是关于模板或嵌套模板的模板成员的事情。。如果解决了这一问题和我遇到的另一个问题,您仍然需要在constexpr之外对它们进行专门化(一些编译器违反了这一规则,例如Mistrosoft的某些版本)。谢谢!
    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";
        }
    }