【问题标题】:GCC5: Nested variable template is not a function template? [duplicate]GCC5:嵌套变量模板不是函数模板? [复制]
【发布时间】:2017-08-10 07:43:53
【问题描述】:

我正在尝试使用 GCC 5.4 (online example) 编译以下 C++14 代码:

template<typename T>
struct traits {
    template<typename X>
    static constexpr bool vect = true;
};

template<typename T1, typename T2>
constexpr bool all_vect = traits<T1>::template vect<T2>;

bool something() {
    return all_vect<void, double>;
}

但我收到以下错误:

<source>: In instantiation of 'constexpr const bool all_vect<void, double>':
<source>:11:12:   required from here
<source>:8:16: error: 'template<class X> constexpr const bool traits<void>::vect<X>' is not a function template
 constexpr bool all_vect = traits<T1>::template vect<T2>;
                ^
<source>:8:16: error: 'vect<T2>' is not a member of 'traits<void>'
Compiler exited with result code 1

虽然我在 GCC 6.1 或更高版本或 clang 3.9 或更高版本中没有问题。但是对于我尝试过的所有版本的 GCC5 来说都是一样的。

我找不到原因?通常,GCC5 应该是完整的 C++14 功能。

在 GCC5 中是否有一个简单的解决方法仍然使用变量模板?我宁愿不再使用简单的特征,因为我将所有特征都转换为使用变量模板。

【问题讨论】:

    标签: c++ gcc c++14


    【解决方案1】:

    这是gcc6中修复的错误,如欺骗所示。

    在保留模板变量的同时似乎没有解决方法。

    对于避开变量模板的解决方法,您可以使用良好的旧静态非模板变量:

    template<typename T>
    struct traits {
    
        template<typename X>
        struct Is_vect
        {
            static constexpr bool value = true;
        };
    };
    
    template<typename T1, typename T2>
    struct Are_all_vect
    {
        static constexpr bool value = traits<T1>::template Is_vect<T2>::value;
    };
    
    
    bool something() {
        return Are_all_vect<void, double>::value;
    }
    

    或 constexpr 模板函数:

    template<typename T>
    struct traits {
        template<typename X>
        static constexpr bool vect() { return true; }
    };
    
    template<typename T1, typename T2>
    constexpr bool all_vect() { return traits<T1>::template vect<T2>(); }
    
    bool something() {
        return all_vect<void, double>();
    }
    

    【讨论】:

    • 感谢您的回答。我实际上一直在寻找一种更简单的解决方法,仍然使用变量模板。我宁愿不再使用简单的特征,因为我将所有特征都转换为使用变量模板。
    • @BaptisteWicht 看起来你唯一的选择是更新版本的编译器修复了错误或回到旧的特征,或者你可以拥有 constexpr 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多