简体   繁体   中英

C++ : define struct/class template differenty for class and non-class types

in my C++ projet, I use a simple struct template with one template argument (a Vec2, with x and y attributes), and I need to define it differently for two main use cases:

  • The type is a class, in which case i need special constructor to initialize the two instances that will be held by forwarding arguments to the constructor of that class
  • The type is not a class (eg any number type, a pointer, etc), in which case i'd like to be able to use aggregate initialization, which is, from what i understand, impossible for a class/struct that has user-defined constructors.

Which brings me to the question: how can i (using C++17) make two different definitions of my class, one for class types and one for others? Can I make some kind of partial specialization for just the class types?

You can add extra parameter to enable SFINAE, something like

template <typename T, typename Enabler = void>
struct Vec2
{
    T x;
    T y;
    // ...
};

template <typename T>
struct Vec2<T, std::enable_if_t<std::is_class_v<T>>>
{
private:
    T x;
    T y;

public:
    Vec2(T x, T y) : x(std::move(x)), y(std::move(y)) {}
    // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM