Will static_if override template specialization?

Some common specialized specialization:

template<class T>
class C
{
    void common() { ... }
    void f2 = delete;
};

template<>
class C<int>
{
    void common() { ... }
    void f1() { ... }
};

It can be represented static_ifas:

template<class T>
class C
{
    void common() { ... }

    static_if(std::is_same<T, int>::value)
    {
        void f1( ) { ... }
    }
    else
    {
        void f2( ) = delete;
    }
}

Are these directly competing features? Can a template specialization do something static_ifit can't? It seems that it static_ifcan do everything that template specialization can do, and much more.

Aside: I do not really like it static_ifin this context, because it potentially makes which parts of the interface available to you in any given case, not obvious. Perhaps the specialized specialization of templates in some cases provides a clearer syntax.

+5
source share
6 answers

, static if , - "" - (= specialize) / ..

+10

, static_if . - , static_if, , static_if . static_if - .

static_if , , , .

struct S {};

template<typename T>
struct T
  static_if(is_same<T,int>::value) { : S }  // ?
{ };

template<typename T>
struct T {};

template<>
struct T<int> : S {};
+4

Ifs - ; . .

Alexandrescu Modern ++ Design, 11.9, "": , , Shape, . , . dynamic_cast, , static_cast, . :

template <typename To, typename From> struct ShapeCaster
{ 
    static To & cast(From & x) { return dynamic_cast<To&>(x); }
};

template <> struct ShapeCaster<Triangle, Shape>
{
    static Triangle & cast(Shape & x) { return static_cast<Triangle&>(x); }
};

template <typename To, typename From> To & shape_cast(From & x)
{
    return ShapeCaster<To, From>::cast(x);
}

, ,

To & y = shape_cast<To>::cast(x);

, .

if .

+2

static if . , , , , , .

, /, - . , static if , , , , , , / .

+1

, . static_if , , , . , - / .

0

, !

: std::is_same<T, int>::value !

, , :

template<typename, typename>
struct is_same{
    static constexpr bool value = false;;
};
 template<typename T>
struct is_same<T, T>{
    static constexpr bool value = true;;
};

Actually the question is, will there finally be a method for comparing types / classes without specializing templates? Maybe only then there will be no need for specialization of templates!

0
source

All Articles