Home > Blockchain >  Can I access a non-type template class argument from outside? How?
Can I access a non-type template class argument from outside? How?

Time:04-25

Please check the following code:

#include <iostream>

template <int Size>
class Test
{
  public:
    // Will not compile, if Size is not a type!
    // error: 'Size' does not name a type
    using MySize = Size;
    double array[Size];
};

using MyTestArray = Test<3>;

int main()
{
    MyTestArray testArray;

    std::cout << "Test array has size " << MyTestArray::MySize << std::endl;

    return 0;
}

Is there any possibility to access Size from outside without introducing a boilerplate getter like this?

constexpr static int getSize() 
{
    return Size;
}

CodePudding user response:

You can define a constexpr static variable with the value of the template parameter inside the class, for example

template <int Size>
class Test
{
  public:
    constexpr static auto MySize = Size;
    double array[Size];
};

Then you access like this

using MyTestArray = Test<3>;
auto size =  MyTestArray::MySize;

CodePudding user response:

You'll need some boilerplate. Either add a static member to Test or if you do not want that or if you cannot modify Test you can use a type trait:

#include <iostream>

template <int Size> class Test {};

template <typename T> struct MySize;
template <int Size> struct MySize<Test<Size>> { static constexpr const int value = Size; };
template <typename T> constexpr const int MySize_v = MySize<T>::value;

int main()
{  
    std::cout << MySize_v<Test<3>>;
}

CodePudding user response:

You can also use the decltype specifier assuming a constness of the MySize variable. An example similar to the above post.

#include <iostream>

using namespace std;

template <int Size>
class Test
{
public:
    static const decltype(Size) MySize = Size;
    double array[Size];
};

using MyTestArray = Test<3>;

int main()
{
    MyTestArray testArray;

    std::cout << "Test array has size " << MyTestArray::MySize << std::endl;

    return 0;
}
  • Related