具有非类型模板参数的构造函数

Constructor with non-type template arguments

this question 中声明不可能直接为 class 构造函数使用模板参数,因为如果你写类似

struct S{
    template<typename T>
    S() { ... }
}

那你就没有办法调用这个构造函数了。但是,有一些解决方法可以使这项工作起作用,例如,通过模板参数推导。

但我所知道的所有这些解决方法都仅适用于类型参数。所以,问题是

是否有任何变通方法可以使此方法适用于非类型模板参数?

struct S{
    template<int x>
    S() { ... }
}

我对应该在现代 C++(C++17 标准,包括所有 TS)中工作的解决方案很感兴趣,因为这是一个理论问题而不是实际问题。

But all of these workarounds I know are for type arguments only

None 的解决方法是特定于类型的 - 重点是在构造函数中添加一些可以推导出来的东西。所以如果我们想要一个类型,我们会做这样的事情:

template <class T> struct tag { };

struct S {
    template <class T>
    S(tag<T>);
};

如果我们想要 int,我们做同样的事情:

template <int I> struct val { };

struct S {
    template <int I>
    S(val<I>);
};

对于值,您甚至不需要想出自己的标签类型 - 您可以在 std::integral_constant.

之上进行 piggy-pack