这是我想做的伪代码.
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 ...;
* }
* };
*/
Run Code Online (Sandbox Code Playgroud)
有什么方法可以禁用主模板并需要使用显式专门化吗?
是的,只是不要定义主要模板:
template <typename> struct ConvertToT;
template <> struct ConvertToT<int>
{
// ...
};
// etc.
Run Code Online (Sandbox Code Playgroud)
如果你喜欢静态断言,你可以获得可编译的代码,你猜对了,一个额外的间接层:
template <typename> struct never_true : std::false_type { };
template <typename T> struct Foo
{
static_assert(never_true<T>::value, "Can't use this.");
};
Run Code Online (Sandbox Code Playgroud)
这适用于完整和不完整类型.
(你也可以使用!std::is_same<T, T>::value.)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |