DarthRubik
DarthRubik

Reputation: 3975

Simplifying template parameters

Take the following struct:

template<typename T,T value>
struct A{
};

I would like to use it like this:

A<12> a;  //A<12> should become A<int,12>

But this is not allowed. Why is it not allowed? (and is there a workaround?)

Upvotes: 0

Views: 63

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69884

Maybe the closest you're going to get is to use a meta-factory:

template<class T, T value>
struct A
{};


template<class T = int>
struct factory
{
  template<T V> using A = ::A<T, V>;
};

int main()
{
  auto x = factory<>::A<12> {};
  auto y = factory<short>::A<45> {};
}

Upvotes: 0

prestokeys
prestokeys

Reputation: 4849

Not sure what you want, but perhaps this?

#include <iostream>

template <typename T, T value>
struct A {
    void foo() const { std::cout << "A<int, " << value << ">::foo called\n"; }
};

// Sample partial specialization that you might want.
template <std::size_t value>
struct A<std::size_t, value> {
    void foo() const { std::cout << "A<std::size_t, " << value << ">::foo called\n"; }
};

template <int N>
using B = A<int, N>;

template <int N, typename T = int>
using C = A<T, static_cast<T>(N)>;

int main() {
    B<12> a;
    a.foo();  // A<int, 12>::foo called
    C<12> c;
    c.foo();  // A<int, 12>::foo called
    C<12, std::size_t> d;
    d.foo();  // A<std::size_t, 12>::foo called
}

Upvotes: 1

Related Questions