C++特征和专业化

发布于 2024-12-28 13:16:56 字数 908 浏览 3 评论 0原文

可能的重复:
我在哪里以及为什么有添加“template”和“typename”关键字?

我第一次尝试使用特征来使我能够在一些通用例程中简洁地关联相关类型。然而,我在语法上遇到了困难,谷歌搜索似乎没有找到任何实现此类事情的简单示例。这是我目前所拥有的简明示例:

template <typename T> struct foo_traits { };

template<> struct foo_traits<int> {
    typedef unsigned char T2; // sub-type for int specialisation of foo_traits
};

template <typename T> T foo(void)
{
    typedef foo_traits<T> traits_type; // OK
    typedef traits_type::T2 T2; // error here: "Too few template-parameter-lists"

    T i
    T2 j;

    // ...
}

What is the right way to get the T2 typedef from foo_traits so that I can use it in my generic template function foo ?

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

I'm trying to use traits for the first time to enable me to succinctly associate related types in some generic routines. However I'm struggling with the syntax and Googling doesn't seem to turn up any simple examples for implementing this kind of thing. Here is condensed example of what I have currently:

template <typename T> struct foo_traits { };

template<> struct foo_traits<int> {
    typedef unsigned char T2; // sub-type for int specialisation of foo_traits
};

template <typename T> T foo(void)
{
    typedef foo_traits<T> traits_type; // OK
    typedef traits_type::T2 T2; // error here: "Too few template-parameter-lists"

    T i
    T2 j;

    // ...
}

What is the correct way to get the T2 typedef from foo_traits so that I can use it in my generic template function foo ?

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

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

发布评论

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

评论(1

吹泡泡o 2025-01-04 13:16:56

奇怪的错误消息,但您确实必须告诉编译器嵌套的 T2 应该是类型名称

typedef typename traits_type::T2 T2;

Odd error message, but you really have to tell the compiler that the nested T2 is supposed to be a type name

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