c++ - Why can't I specialize with a nullptr template parameter on a dependent type? -
this question has answer here:
i'd make specialization of struct 1 uses function pointer , doesn't. when this:
template <typename t, t*> struct test; template <typename t> struct test<t, nullptr> { }; template <typename r, typename...args, r(*fn)(args...)> struct test<r(args...), fn> { };
i error:
error: type 't*' of template argument 'nullptr' depends on template parameter struct test<t, nullptr>
what mean , how make work?
the linked question describes main issue , solutions, since involved i've applied them particular problem.
version 1
we can use std::integral_constant
hold pointers, can leverage fact around restriction on non-type parameters:
template <typename t, typename u> struct test; template <typename t> struct test<t, std::integral_constant<t*,nullptr>> { void operator()() { std::cout << "nullptr" << std::endl; } }; template <typename r, typename...args, r(*fn)(args...)> struct test<r(args...), std::integral_constant<r(*)(args...),fn>> { void operator()() { std::cout << "fnptr" << std::endl; } };
unfortunately usage looks pretty ugly, works:
test<int,std::integral_constant<int*,nullptr>> a; a(); test<decltype(foo), std::integral_constant<decltype(&foo), foo>> b; b();
version 2
this version uses std::enable_if
checking rather partial specialization:
template <typename t, t*, typename = void> struct test; template <typename t, t* p> struct test<t, p, typename std::enable_if<(p==nullptr)>::type> { void operator()() { std::cout << "nullptr" << std::endl; } }; template <typename t, t* p> struct test<t, p, typename std::enable_if<std::is_function<t>::value>::type> { void operator()() { std::cout << "fnptr" << std::endl; } };
the usage of intended:
test2<int, nullptr> c; c(); test2<decltype(foo), foo> d; d();
with version don't have instant access parameter types of function pointers used template arguments, write other trait them if necessary.
here's live demo shows both versions working.
Comments
Post a Comment