具有非类型模板参数的构造函数 [英] Constructor with non-type template arguments
问题描述
在此问题中,它表明不可能仅将模板参数直接用于类构造函数,因为如果你写类似
In this question it's stated that it's impossible to just directly use template arguments for class constructor, because if you write something like
struct S{
template<typename T>
S() { ... }
}
然后,您将无法调用此构造函数.但是,有一些变通办法可以使此工作生效,例如,通过模板参数推导.
Then you have no way of calling this constructor. However, there're some workarounds to make this work, for example, through template argument deduction.
但是我所知道的所有这些变通方法仅适用于类型实参.所以,问题是
But all of these workarounds I know are for type arguments only. So, the question is
是否有任何变通办法可以使非类型模板参数起作用?
struct S{
template<int x>
S() { ... }
}
我对应该在现代C ++(C ++ 17标准,包括所有TS)中使用的解决方案感兴趣,因为这是一个理论问题,而不是实践问题.
I'm interested in solutions which should work in modern C++ (C++17 standard, including all TS), as this is a theoretical rather than practical question.
推荐答案
但是我知道的所有这些变通方法仅适用于类型参数
But all of these workarounds I know are for type arguments only
解决方法都不是特定于类型的-关键是在构造函数中粘贴一些可以推论的内容.因此,如果需要类型,可以执行以下操作:
None of the workarounds are type-specific - the point is to stick something in the constructor that can be deduced. So if we want a type, we do something like:
template <class T> struct tag { };
struct S {
template <class T>
S(tag<T>);
};
,如果我们想要一个 int
,我们可以做同样的事情:
and if we want an int
, we do the same thing:
template <int I> struct val { };
struct S {
template <int I>
S(val<I>);
};
对于值,您甚至不需要自己的标记类型-您可以在 std :: integral_constant
的顶部打包.
For values, you don't even need to come up with your own tag type - you can piggy-pack on top of std::integral_constant
.
这篇关于具有非类型模板参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!