Constructor with non-type template arguments

╄→尐↘猪︶ㄣ 提交于 2019-12-31 03:17:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!