简化模板参数

时间:2016-05-14 21:40:07

标签: c++ templates

采用以下结构:

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

我想像这样使用它:

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

但这是不允许的。为什么不允许? (有解决方法吗?)

2 个答案:

答案 0 :(得分:1)

不确定你想要什么,但也许这个?

#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
}

答案 1 :(得分:0)

也许您最接近的是使用元工厂:

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> {};
}