通过一个失败的模板参数 [英] Pass a Failing Template Argument
问题描述
Dan 对此问题的回答:有什么像模板化的案例声明需要一个 DefaultType
模板参数。
例如,给定这个模板化的函数:
模板< typename T,typename R = enable_if_t< is_integral< T> :: value,int>
R foo(T bar){return static_cast< R>(bar);}
这个代码将编译得很好: foo(13)
但是这个代码将失败: foo(13.0)
。
foo(13.0)
在编译时失败的原因是 enable_if_t
未定义。是否有一个名称为未定义,我可以传递到上述 DefaultType
?
可以通过调用 foo< int,undefined>(13)
并让它失败,如果事实上 undefined
是我要找的类型。
编辑:
需要更多解释。
Dan 的`static_case可以这样调用:
模板< 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);}
我想传递undefined参数,以使其在评估该参数时无法仅编译 。 (标记为default case的参数。)
在我的简单测试中,任何两个参数传递给 foo
(例如 foo< int,int>(13);
)我想要一个模拟 enable_if_t
foo< double>(13.0); )在示例中我说调用 foo< in,undefined> (13)
。我只想知道未定义是什么。
最简单的方法是 undefined
类型是:
std :: enable_if_t< false>
所以你可以调用你的 foo
this:
foo< int,std :: enable_if_t< false>>(13)
并且按照您的要求失败。
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.
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.
这篇关于通过一个失败的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!