Pass a Failing Template Argument

心已入冬 提交于 2019-12-25 01:04:28

问题


Dan's answer to this question: Is There Anything Like a Templatized Case-Statement takes a DefaultType template parameter.

Is it possible to pass something there which will force a compile time fail?

For example, given this templatized function:

template <typename T, typename R = enable_if_t<is_integral<T>::value, int>>
R foo(T bar) {return static_cast<R>(bar);}

This code will compile fine: foo(13) But this code will fail: foo(13.0).

The reason that foo(13.0) will fail at compile time is that enable_if_t is undefined. Is there a name for "undefined" that I can pass to the afore mentioned DefaultType?

If so I should be able to test this by calling foo<int, undefined>(13) and having it fail, if in fact undefined was the type I'm looking for.

EDIT:

Apparently more explanation is called for.

Dan's `static_case can be called like this:

template<class T>
typename static_switch<sizeof(T),
                       int, // default case
                       static_case<sizeof(char),char>,
                       static_case<sizeof(short),short>,
                       static_case<sizeof(long),long>,
                       static_case<sizeof(long long),long long>>::type foo(T bar){ return reinterpret_cast<decltype(foo(bar))&>(bar);}

I want to pass "undefined" or whatever to that second parameter to make it fail to compile only when that parameter is evaluated. (The parameter marked "default case".)

In my simple test passing any two parameters to foo will succeed (for example foo<int, int>(13);) I want a parameter that would mimic the effect of enable_if_t causing it to fail (like when we call foo<double>(13.0);) In the example I said call foo<in, undefined>(13). I just want to know what "undefined" is.


回答1:


The simplest way to have the undefined type you are talking about is:

std::enable_if_t<false>

So you can call your foo template like this:

foo<int, std::enable_if_t<false>>(13)

And have it fail as you asked.



来源:https://stackoverflow.com/questions/28724017/pass-a-failing-template-argument

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