简化模板参数

Simplifying template parameters

本文关键字:参数      更新时间:2023-10-16

取以下结构:

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

我想这样使用它:

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

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

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

#include <iostream>
template <typename T, T value>
struct A {
    void foo() const { std::cout << "A<int, " << value << ">::foo calledn"; }
};
// 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 calledn"; }
};
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
}

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

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