c++templatesc++14variable-templates

how to create a variable-template?


#include <iostream>
using namespace std;

template<int base, int x>
struct Power {


    static constexpr int a = base * (Power<base, x - 1>::a);

};

template<int base>
struct Power<base, 0> {


static constexpr int a = 1;

};

///////////////////////////////// I failed in creating a variable-template here.

template<int base, int x>       
using power_v = typename Power<base, x>::a;

/////////////////////////////////

int main()
{
    constexpr int y = power_v<3, 2>;

    cout << y;
}

Solution

  • using is used for declaring type alias.

    Type alias is a name that refers to a previously defined type (similar to typedef).

    Alias template is a name that refers to a family of types.

    As variable_template it should be

    template<int base, int x>       
    constexpr int power_v = Power<base, x>::a;
    

    LIVE