首页 > 解决方案 > 如何防止用户指定函数模板参数,强制推导它?

问题描述

假设我有一个模板函数:

template <typename A, typename B>
A fancy_cast(B)
{
    return {};
}

预期用途类似于fancy_cast<int>(1.f).

但是没有什么能阻止用户手动指定第二个模板参数:fancy_cast<int, int>(1.f),这会导致问题。

如何防止typename B被指定并强制推断?

我想出了这个:

// Using this wrapper prevents the code from being
// ill-formed NDR due to [temp.res]/8.3
template <auto V> inline constexpr auto constant_value = V;

template <
    typename A,
    typename ...Dummy,
    typename B,
    typename = std::enable_if_t<constant_value<sizeof...(Dummy)> == 0>
>
A fancy_cast(B)
{
    return {};
}

它似乎工作,但它非常麻烦。有没有更好的办法?

标签: c++

解决方案


制作fancy_cast变量模板怎么样?

template <typename A>
struct fancy_cast_t {
    template <typename B>
    A operator()(B x) const { return x; }
};

template <typename A>
constexpr fancy_cast_t<A> fancy_cast {};

fancy_cast<int>(1.5);  // works
fancy_cast<int, int>(1.5);  // doesn't work
fancy_cast<int>.operator()<int>(1.5);  // works, but no one would do this

推荐阅读