问题
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
Are there any workarounds to make this work for non-type template arguments?
struct S{
template<int x>
S() { ... }
}
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.
回答1:
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>);
};
and if we want an int
, we do the same thing:
template <int I> struct val { };
struct S {
template <int I>
S(val<I>);
};
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
.
来源:https://stackoverflow.com/questions/43211721/constructor-with-non-type-template-arguments