【问题标题】:Is there any difference between "T" and "const T" in template parameter?模板参数中的“T”和“const T”有什么区别吗?
【发布时间】:2012-03-29 13:31:39
【问题描述】:

以下两种语法有什么区别:

template<int N> struct A;         // (1)

template<const int N> struct A;   // (2)

关于何时使用每种语法的任何一般准则?

【问题讨论】:

    标签: c++ templates syntax constants


    【解决方案1】:

    没有。

    §14.1 [temp.param] p5

    [...] template-parameter 上的顶级 cv-qualifiers 在确定其类型时会被忽略。

    【讨论】:

    • 仅适用于typename 参数种类吗? (见我的回答)。我无法访问该标准,而且在我的草稿中找到有用信息方面相当糟糕。
    • @J.N.:不,这句话专门指非类型模板参数(无论如何你不能有const typename:P)。
    • 接受您的回答。为了完整起见,您可能需要更新编码指南。
    • @iammilind:你说的是哪些编码指南?
    • 虽然暗示const任何 情况下都没有用,但您的回答只是谈论它们之间的比较。值得一提的是何时使用哪个版本(即始终使用 1st)。这是你的愿望:)。仅供未来/新手访问者参考。
    【解决方案2】:

    我发现这是在快速搜索标准:

    template<const short cs> class B { };
    template<short s> void g(B<s>);
    void k2() {
        B<1> b;
        g(b); // OK: cv-qualifiers are ignored on template parameter types
    }
    

    评论说它们被忽略了。

    我建议不要在模板参数中使用const,因为它是不必要的。请注意,它也不是“暗示”的——它们是不同于const 的常量表达式。

    【讨论】:

    • 评论不规范。
    【解决方案3】:

    int 的选择可能是个坏主意,但它对指针有影响:

    class A
    {
    public:
        int Counter;
    };
    
    A a;
    
    
    template <A* a>
    struct Coin
    {
        static void DoStuff()
        {
            ++a->Counter; // won't compile if using const A* !!
        }
    };
    
    Coin<&a>::DoStuff();
    cout << a.Counter << endl;
    

    【讨论】:

    • 如果我相信其他人的答案,该标准似乎与我的编译器 (GCC 4.6.1 / ubuntu) 不一致:/
    • 别担心,我也可能误解了标准。而@Pubby 的回答只表示匹配模板时会被忽略。
    • const A* 不是const 的合格版本A*。它是一种不相关的类型。 A* constconst 的合格版本A*
    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2021-06-02
    • 2011-05-30
    • 2019-09-04
    • 2012-03-10
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多