“重新定义"默认模板参数 [英] "Redefinition" of default template parameter

查看:158
本文介绍了“重新定义"默认模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用Visual C ++ 2010的以下代码,我有一个奇怪的编译警告:

I have a strange compilation warning for the following code, with Visual C++ 2010:

#include <iostream>

class test
{
    public:
        template<class obj>
        class inner
        {
        private:
            // Line 11:
            template<int index, bool unused = true> struct AttributeName;

        private:
            template<bool b>
            struct AttributeName<0,b>
            {
                static inline const char* get()
                {
                    return "prop";
                }
            };

        public:
            typedef AttributeName<0> propname;
        };
        typedef inner<test> description;
};

int main()
{
    test t;
    std::cout << test::description::propname::get(); // Line 32
    return 0;
}

警告:

file.cpp(11) : warning C4348: 'test::inner<obj>::AttributeName' : redefinition of default parameter : parameter 2 (with [ obj=test ])
file.cpp(11) : see declaration of 'test::inner<obj>::AttributeName' (with [ obj=test ])
file.cpp(32) : see reference to class template instantiation 'test::inner<obj>' being compiled (with [ obj=test ])

我不明白的是,AttributeName重新定义"与定义在同一行...听起来像个错误

What I don't understand is that AttributeName "redefinition" is at the same line than the definition... sounds like a bug

我注意到将inner设置为非模板类​​可以删除该警告.但是,这不是一个选择,因为实际代码比该测试用例要复杂得多,需要进行模板化.

I noticed that making inner a non-template class removes the warning. However, this is not an option since the real code is more complicated than this testcase and need to be templated.

此外,如果将警告视为错误,则不会编译此代码...

Also, this code won't compile if warning are treated as errors...

它在GCC上编译时没有警告.

为什么msvc输出此类警告,并且有解决方法?

Why msvc is outputing such warning and is there a workaround ?

修改

以下修改:

template<int index, bool unused = true> struct AttributeName {};

似乎可以消除警告.

推荐答案

这主要是猜测,因为这似乎可以解决(?):

This is mostly a guess, as this seems to solve(?) it:

template<int index, bool unused = true> struct AttributeName;
template<int index, bool unused> struct AttributeName
{
};

我的猜测是,前向声明被视为声明和定义",因为它看不到其他任何内容,因此即使同一行,也抱怨默认设置为重新定义".尽管2012年的表现相同,但可能是无意的.

My guess is that the forward declaration is seen as both a declaration and a "definition" since it can't see anything else, hence it complains about the default being "redefined" even though it's the same line. Could be unintentional, although 2012 behaves the same.

这篇关于“重新定义"默认模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆