如何强制客户端调用显式专用模板而不是主模板? [英] How can I force a client to call an explicitly specialized template instead of the primary template?
本文介绍了如何强制客户端调用显式专用模板而不是主模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我想要做的伪代码。
template< typename T&
struct ConvertToT
{
static_assert(false,T需要显式专用化。
//在调用Convert之前,变体将被强制转换为此类型。
std :: uint32_t GetVariantType()
{
return VT_EMPTY;
}
T Convert(CComVariant& input)
{
returnERROR!
}
};
模板<>
struct ConvertToT< std :: wstring>
{
std :: uint32_t GetVariantType()
{
return VT_BSTR;
}
T Convert(CComVariant&input)
{
return std :: wstring(input.bstrVal,:: SysStringLen(input.bstrVal));
}
};
/ *对几个更明确的专业化重复:
* template<>
* struct ConvertToT< ...>
* {
* std :: uint32_t GetVariantType()
* {
* return ...;
*}
* ...转换(CComVariant& input)
* {
* return ...;
*}
*};有没有一些方法,我可以禁用主模板,并要求使用一个?显式专门化?解决方案是的,只是不要定义主模板:
模板< typename> struct ConvertToT;
模板<> struct ConvertToT< int>
{
// ...
};
//等。
如果你喜欢静态断言,获得可编译代码,你猜到了,一个额外的间接层次:
template< typename> struct never_true:std :: false_type {};
template< typename T> struct Foo
{
static_assert(never_true< T> :: value,Can not use this。);
};
这适用于完整和不完整的类型。
(您也可以使用!std :: is_same< T,T> :: value
。)
This is pseudocode for what I want to do.
template<typename T>
struct ConvertToT
{
static_assert(false, "Explicit specialization for T required.");
// Variant will be coerced to this type before calling Convert.
std::uint32_t GetVariantType()
{
return VT_EMPTY;
}
T Convert(CComVariant& input)
{
return "ERROR!";
}
};
template<>
struct ConvertToT<std::wstring>
{
std::uint32_t GetVariantType()
{
return VT_BSTR;
}
T Convert(CComVariant& input)
{
return std::wstring(input.bstrVal, ::SysStringLen(input.bstrVal));
}
};
/* repeat for several more explicit specializations:
* template<>
* struct ConvertToT<...>
* {
* std::uint32_t GetVariantType()
* {
* return ...;
* }
* ... Convert(CComVariant& input)
* {
* return ...;
* }
* };
*/
Is there some way I can disable the primary template and require use of an explicit specialization?
解决方案 Yes, just don't define the primary template:
template <typename> struct ConvertToT;
template <> struct ConvertToT<int>
{
// ...
};
// etc.
If you like a static assertion, you can get compilable code with, you guessed it, one extra level of indirection:
template <typename> struct never_true : std::false_type { };
template <typename T> struct Foo
{
static_assert(never_true<T>::value, "Can't use this.");
};
This works for both complete and incomplete types.
(You can also use !std::is_same<T, T>::value
.)
这篇关于如何强制客户端调用显式专用模板而不是主模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文