【发布时间】:2014-09-17 03:10:49
【问题描述】:
这个问题的灵感来自最近出现的question about extended std::is_base_of type trait。
有什么技术可以让我们在现代 C++ 或其扩展中区分普通模板参数和模板模板参数(例如,-std=gnu++1zclang++/g++)?
namespace details
{
template< /* ??? */ base >
struct is_derived_from;
template< typaneme base >
struct is_derived_from< base >
{
static std::true_type test(base *);
static std::false_type test(void *);
};
template< template< typename ...formal > base >
struct is_derived_from< /* ??? */ >
{
template< typename ...actual > // actual parameters must be here!
static std::true_type test(base< actual... > *);
static std::false_type test(void *);
};
} // namespace details
template< typename derived, /* ??? */ base >
using is_derived_from = decltype(details::is_derived_from< /* ? base< ? > */ >::test(std::declval< typename std::remove_cv< derived >::type * >()));
在积极的情况下,它允许我们使一些有用的类型特征更加强大(例如,STL 的std::is_base_of)。
我认为它需要一种语言特性作为“通用类型名”,不是吗?
【问题讨论】:
-
你不能重载类模板。不过,我认为您可以使用重载
constexpr函数模板。 -
@T.C.它们之间是否存在我们可以利用的根本差异?
-
@T.C.您不需要
constexpr,只需在decltype内部进行重载解析,无需评估。 -
@Potatoswatter 但是如果您希望能够同时执行
foo<Template, Derived>和foo<BaseClass, Derived>并在编译时使用结果,那么您需要使用一对constexpr函数,不? -
@T.C.只要存在重载决议,您就可以将
constexpr int foo() { return 1; }替换为std::integral_constant< int, 1 > foo(); // no definition。不要判断哪个更好,您只是不需要需要constexpr:P 。不过后者可能更便携。
标签: c++ templates c++11 sfinae typetraits