c++ - With templates, how to differentiate two parallel cases, such as between floating point types and integral types? -


cppreference.com ( http://en.cppreference.com/w/cpp/types/enable_if#notes ) notes that:

a common mistake declare 2 function templates differ in default template arguments. illegal because default template arguments not part of function template's signature, , declaring 2 different function templates same signature illegal.

struct t {     enum { int_t,float_t } m_type;     template <typename integer,               typename = std::enable_if_t<std::is_integral<integer>::value>     >     t(integer) : m_type(int_t) {}      template <typename floating,               typename = std::enable_if_t<std::is_floating_point<floating>::value>     >     t(floating) : m_type(float_t) {} // error: cannot overload }; 

so true… correct approach solve issue , achieve above incorrect code fails achieve?

i believe work:

#include <type_traits>  struct t {     enum { int_t,float_t } m_type;     template <typename integer,               std::enable_if_t<std::is_integral<integer>::value>* = nullptr     >     t(integer) : m_type(int_t) {}      template <typename floating,               std::enable_if_t<std::is_floating_point<floating>::value>* = nullptr     >     t(floating) : m_type(float_t) {} // overload valid };  int main() {     t t = int{};     t t2 = float{};     (void)t;     (void)t2; } 

[live demo]


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -