gpt4 book ai didi

C++ 模板特化

转载 作者:太空狗 更新时间:2023-10-29 20:18:26 26 4
gpt4 key购买 nike

您好!有人知道实现或模仿以下行为的方法吗?(此代码会导致编译时错误)。

例如,我只想在派生类中添加特定的模板特化。

struct Base {
template <typename T> void Method(T a) {
T b;
}

template <> void Method<int>(int a) {
float c;
}
};

struct Derived : public Base {
template <> void Method<float>(float a) {
float x;
}
};

最佳答案

重载怎么样

struct Base {
template <typename T> void Method(T a) {
T b;
}

void Method(int a) {
float c;
}
};

struct Derived : public Base {
using Base::Method;
void Method(float a) {
float x;
}
};

不能像您的示例中那样添加显式特化。此外,您的基类格式不正确,因为您必须在类范围之外定义任何显式特化

struct Base {
template <typename T> void Method(T a) {
T b;
}
};

template <> void Base::Method<int>(int a) {
float c;
}

所有显式特化都需要给出要特化的模板的名称,或者与模板在同一范围内。您不能像那样在派生类中编写显式特化。

关于C++ 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005086/

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