gpt4 book ai didi

c++ - 成员模板特化及其范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:14 24 4
gpt4 key购买 nike

在我看来,C++ 不允许在命名空间和全局范围以外的任何范围内对成员模板进行专门化(MS VSC++ 错误 C3412)。但对我来说,在派生类中专门化基类的主要成员模板是有意义的,因为派生类就是这样做的——专门化基类中的东西。例如,请考虑以下示例:

struct Base
{
template <class T>
struct Kind
{
typedef T type;
};
};

struct Derived : public Base
{
/* Not Allowed */
using Base::Kind;
template <>
struct Kind <float>
{
typedef double type;
};
};

int main(void)
{
Base::Kind<float>::type f; // float type desired
Derived::Kind<float>::type i; // double type desired but does not work.
}

我的问题是为什么不允许这样做?

最佳答案

我明白你想做什么,但你做的不对。试试这个:

struct Base{};
struct Derived{};

// Original definition of Kind
// Will yield an error if Kind is not used properly
template<typename WhatToDo, typename T>
struct Kind
{
};

// definition of Kind for Base selector
template<typename T>
struct Kind<Base, T>
{
typedef T type;
};

// Here is the inheritance you wanted
template<typename T>
struct Kind<Derived, T> : Kind<Base, T>
{
};

// ... and the specialization for float
template<>
struct Kind<Derived, float>
{
typedef double type;
};

关于c++ - 成员模板特化及其范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/808403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com