【问题标题】:Content of class method determined by the template value由模板值决定的类方法的内容
【发布时间】:2022-01-20 04:30:10
【问题描述】:

通过使用 c++ 14 或 c++11,我们是否有一种优雅的方法来完成以下任务?成员数量和操作类型由模板输入值'count'决定

    template<int count>
    class show{
    public:
        run(){
            if (count == 1){
                int x;
            } else if(count ==2){
                int x, y;
            }else if(count ==3){
                int x, y, z;
            } 

            if (count == 1){
                printf("res: %d \n", x);
            } else if(count ==2){
                printf("res: %d \n", x+y);
            }else if(count ==3){
                printf("res: %d \n", x+y+z);
            } 

        }
    };

更新:在这种情况下我们可以使用部分特化或与模板相关的东西吗?

【问题讨论】:

  • 你的意思是if constexpr,即编译时 if 或 sth else?
  • 部分特化对这种情况有用吗?我不熟悉这个...
  • 如果您希望每个成员都是单独的变量,您是否考虑过en.cppreference.com/w/cpp/types/enable_if?如果 count 为
  • 当然,为什么不 godbolt.org/z/6fdjj1j3c if constexpr 应该等同于这个(前提是您使用 C++17 或更高版本;如果您仅限于 C++14,则需要专业化),这是一个口味问题,一个人需要使用其中一个或另一个。你能提供更多关于你的问题的细节吗?
  • 如果都属于同一类型,为什么不使用大小为count 的vector 并总结一下?

标签: c++ templates partial-specialization


【解决方案1】:

是的,您可以使用专业化:

template<int count>
class show;

template<>
class show<1>{
    int x;
    public:
    show(int _x):x{_x}{}
    void run(){
        std::cout << "val of x " << x << std::endl;
    }   
};



template<>
class show<2>{
    int x,y;
    public:
    show(int _x, int _y):x{_x}, y{_y}{}
    void run(){
        std::cout << "add " << x+y << std::endl;
    }   
};

但你也可以让它更通用:

template <int count>
class simply
{
    std::array<int, count> arr;

    public:
    template < typename ... T > 
        simply( T ... in ): arr{ in... } {}

    void run()
    {   
        std::cout << [this](){ int sum=0; for( auto el: arr ){ sum+=el; } return sum; }() << std::endl;
    }   
};

要使用上面的所有东西:

int main() {
    show<1> s1(10);
    show<2> s2(100,200);

    s1.run();
    s2.run();

    simply<4> si( 1,2,3,4 );
    si.run();
}

备注: 您应该向simply 添加更多内容,以检查所有int 类型的参数是否带有sfinae 或static_assert。但他是另一个问题......

【讨论】:

    【解决方案2】:

    在您的情况下,数组 (std::array) 似乎合适:

    template <std::size_t count>
    class show
    {
    public:
        std::array<int, count> data{};
        // ...
        void run()
        {
            const int sum = std::accumulate(data.begin(), data.end(), 0);
            printf("res: %d \n", sum);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多