方法模板从类模板完全专业化

发布于 2024-10-06 04:20:06 字数 549 浏览 3 评论 0原文

我知道这个主题现在应该已经过时了,但我在这个具体案例上遇到了困难。

开门见山,这就是我想做的:

enum MyEnum
{
    E_1,
    E_2
};

template <MyEnum T>
class MyClass
{
    // method to be fully specialized
    template <typename U>
    void myMethod(U value);
};

// full specialization of method template from class template
// (or is this in fact partial, since I'm leaving T alone?)
template <MyEnum T>
template <>
void MyClass<T>::myMethod<int>(int value)
{
    std::cout << value << '\n';
}

这可能吗?

I know this subject should be pretty much dated by now, but I'm having a tough time with this specific case.

Straight to the point, this is what I want to do:

enum MyEnum
{
    E_1,
    E_2
};

template <MyEnum T>
class MyClass
{
    // method to be fully specialized
    template <typename U>
    void myMethod(U value);
};

// full specialization of method template from class template
// (or is this in fact partial, since I'm leaving T alone?)
template <MyEnum T>
template <>
void MyClass<T>::myMethod<int>(int value)
{
    std::cout << value << '\n';
}

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-10-13 04:20:06

C++03 [$14.7.3/18] 说

在类模板的成员或出现在命名空间范围中的成员模板的显式特化声明中,成员模板及其某些封闭类模板可能保持非特化,除非该声明不应显式特化类成员模板,如果它的封闭类模板也没有显式专门化

所以你也需要专门化封闭类。

像这样的东西会起作用。

template <>
template <>
void MyClass<E_1>::myMethod<int>(int value)
{
    std::cout << value << '\n';
}

C++03 [$14.7.3/18] says

In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

So you need to specialize the enclosing class too.

Something like this would work.

template <>
template <>
void MyClass<E_1>::myMethod<int>(int value)
{
    std::cout << value << '\n';
}
情徒 2024-10-13 04:20:06

由于您离开 T,而仅专门化函数模板,那么您尝试做的事情将被称为部分专门化,因为 T 仍然是模板化的,您可以在函数中使用它。但不幸的是,函数的部分模板特化(无论是成员函数还是非成员函数)是不允许的。所以你的代码会给出编译错误。

您要么通过专门化类模板来完全专门化,要么根本不专门化。

Since you leave T, while specializing only function template, then what you're trying to do would be called partial specialization, because T is still templated and you can use it in your function. But unfortunately, partial template specialization of function (whether be it member function or non-member function) is not allowed. So your code would give compilation error.

Either you fully specialize by specializing the class template as well, or you don't at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文