【问题标题】:C++ using-declaration for non-type function templates of template base class模板基类的非类型函数模板的C++ using-declaration
【发布时间】:2016-02-04 09:51:50
【问题描述】:

阅读了关于 SO 的几个答案(例如 herehere),我想出了在模板库中调用函数模板的两种常用替代方法:

template<typename T>
struct Base
{
    template<int N>
    auto get() const
    {
        return N;   
    }
};

template<typename T>
struct Derived : public Base<T>
{
    //first alternative
    auto f0() const { return this-> template get<0>(); }   

    //second alternative
    auto f1() const { return Base<T>::template get<1>(); }    
};

DEMO

但是对于非模板函数,是否也有与using Base&lt;T&gt;::foo 声明等效的方法?也许像

template<int N>
using Base<T>::template get<N>;  //does not compile in gcc

【问题讨论】:

  • CWG 109
  • @T.C.所以它不是标准的一部分,我的部分(!)答案只显示了 VS2015 提供的扩展?

标签: c++ templates inheritance


【解决方案1】:

作为using 的替代方案,您可以使用以下内容重新声明该函数:

template<int N> auto get() const{ return Base<T>::template get<N>(); }

此代码适用于 VS2015,但不适用于 coliru:

using Base<T>::template get;
template<int N>
auto f3() { return get<N>(); }

根据我在阅读commenty by T.C. 后的理解,这是 VS2015 的自定义扩展,其行为不是标准的一部分,甚至可能被视为格式错误


【讨论】:

    【解决方案2】:

    我也无法让它与您的using 一起使用。但是,如果目的是简化繁琐的调用语法,那么您可能会发现以下替代方法很有用。我认为它会产生类似的效果。

    template<typename T> 
    struct Base 
    { 
        template<int N> 
        auto get() const 
        { 
            return N;    
        } 
    }; 
    
    template<typename T> 
    struct Derived : public Base<T> 
    { 
        auto f0() const  
        {  
            auto get_0 = Base<T>::template get<0>; 
    
            get_0(); 
        }    
    
        //second alternative 
        auto f1() const  
        {  
            auto get_1 = Base<T>::template get<1>; 
    
            get_1(); 
        }     
    }; 
    
    int main() 
    { 
        return 0; 
    } 
    

    【讨论】:

    • 感谢您的努力,这很清楚。还可以在类范围内定义template&lt;int N&gt; auto get() const {return this-&gt; template get&lt;N&gt;(); }(可能等同于非常量版本的get)。问题是明确地关于模板化 using 声明。
    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2010-12-20
    • 1970-01-01
    相关资源
    最近更新 更多