简体   繁体   中英

Reference to template type in template parameter

If I have a template class A, like this

template <int n>
class A{
    /* some code */
};

Is it possible to have a template class B, that takes a reference or pointer to an A as parameter without having the int n as template parameter in B.

The following code would work:

template <int n, A<n> &a>
class B{
    /* some code */
};

But to use this, I always have to supply 2 parameters to B, which would work, but is inconvenient.

In c++17 using auto would work like this

template <auto &a>
class B{
    /* some code */
};

But I have to work with the arm-none-eabi-gcc which apparently does not support c++17.

So I'd like to know, if there is any other way of creating such a template, so that B only needs 1 template argument.

If I understood you correctly, the goal is to get the template argument of A and make sure that the type B is instantiated with is actually an A . You can do this with some simple metaprogramming by defining your own type traits for A .

#include <type_traits>

template <int n>
class A {};

template <typename T>
struct is_A : std::false_type {};

template <int m>
struct is_A<A<m>> : std::true_type {
    static constexpr int const n = m;
};

template <typename A>
class B {
    static_assert(is_A<A>::value,"!");
    static constexpr int const n = is_A<A>::n;
};

int main() {
    B<A<1>>{};
}

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM