【问题标题】:Is it possible for a class member function argument list to be dependent on a template argument?类成员函数参数列表是否可能依赖于模板参数?
【发布时间】:2020-05-23 23:22:48
【问题描述】:

有没有办法编写一个模板类,以便成员函数的签名/原型依赖于模板参数?例如,如果我声明一个类foo 接受一个int N 模板参数,那么成员函数foo::bar() 的原型是否有可能有N 个相同类型的参数?我知道我可以将std::array 或std::vector 作为参数传递,但在应用程序中我认为这行不通。

template <int N>
class foo {
    std::array<float, N> _data;

 public:
    foo()  {};
    ~foo() {};

    void bar(float arg0, float arg1, float arg2 /*, ... */) const;
};

【问题讨论】:

    标签: c++ class c++11 templates signature


    【解决方案1】:

    使用 c++17,您可以使用类似 std::enable_if_t 的内容,如下所示

    #include <array>
    #include <type_traits>
    
    template <int N>
    class Foo {
        std::array<float, N> _data;
    
    public:
        explicit Foo( const std::array<float, N> & data): _data{data}{
    
        }
        template<typename ...Args>
        std::enable_if_t<sizeof...(Args)== N && std::is_same_v<std::common_type_t<Args...>, float>, void> bar(Args ... args) const{
    
        }
    };
    
    int main(){
        std::array<float, 3> data {.1, .3, .6};
        Foo<3> f {data};
        f.bar(data[0],data[1],data[2]);
        f.bar(1.0);//won't compile
        f.bar(1, 2, 3);//won't compile
    
    
    }
    

    【讨论】:

    • 谢谢,它很有帮助,但它并没有真正解决我想到的问题,这是我的错,因为问题缺少一些细节。我会将其标记为正确答案并提出一个新问题,并详细解释我想要达到的目标:stackoverflow.com/questions/61990155/…
    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2018-12-16
    • 2014-06-07
    • 1970-01-01
    相关资源
    最近更新 更多