代码之家  ›  专栏  ›  技术社区  ›  canellas

仅使用类型参数的变量模板

c++
  •  3
  • canellas  · 技术社区  · 7 年前

    我想这样做:

    #include <iostream>
    
    class a {
    
    public:
        a() : i(2) {}
    
        template <typename ...ts>
        void exec() {
            f<ts...>();
            std::cout << "a::()" << std::endl;
        }
    
        int i;
    private:
    
        template <typename t>
        void f() {
            i += t::i;
        }
    
        template <typename t, typename ...ts>
        void f() {
            f<t>();
            f<t, ts...>();
        }
    };
    
    struct b {
        static const int i = -9;
    };
    
    struct c {
        static const int i = 4;
    };
    
    
    int main()
    {
        a _a;
    
        _a.exec<b,c>();
    
        std::cout << _a.i << std::endl;
    }
    

    其思想是从一组类中获取相同的信息,而不需要每个类的对象。

    有人知道是否有可能吗?

    谢谢!

    3 回复  |  直到 7 年前
        1
  •  5
  •   bartop    7 年前

    如果你的编译器不支持C++ 17:

    template <typename ...ts>
    void f() {
        for ( const auto &j : { ts::i... } )
            i += j;
    }
    
        2
  •  3
  •   Jarod42    7 年前

    在C++ 17中,您的类将仅仅是

    class a {
    
    public:
        a() : i(2) {}
    
        template <typename ...ts>
        void exec() {
            ((i += ts::i), ...); // Folding expression // C++17
            std::cout << "a::()" << std::endl;
        }
    
        int i;
    };
    

    在C++ 11中也是可能的,但是更冗长。

        3
  •  1
  •   Piotr Siupa    7 年前

    代码未编译的原因:

    1. 专门化模板的语法稍有不同。
    2. 你需要把最一般的情况放在第一位。
    3. 不能部分地专门化函数,只能指定类。
    4. 类内不允许部分专用化,只允许在命名空间中进行。

    这里是C++ 11的一个例子。

    #include <iostream>
    
    template<typename t, typename ...ts>
    class a {
    public:
        static constexpr int x = t::i + a<ts...>::x;
    };
    
    template<typename t>
    class a<t> {
    public:
        static constexpr int x = 2 + t::i;
    };
    
    struct b {
        static constexpr int i = -9;
    };
    
    struct c {
        static constexpr int i = 4;
    };
    
    int main()
    {
        constexpr int result = a<b,c>::x;
        std::cout << result << std::endl;
    }
    

    请记住,模板是在编译期间计算的,因此,为了优化起见,最好以允许 constexpr .