简体   繁体   English

有没有一种方法可以为容器类型创建操作符/函数重载

[英]Is there a way to create operator/function overload for container type

I have some class like: 我有一些像这样的课程:

class A {
A& operator=(const A& a);
A& operator=(const int a);
A& operator=(const std::string& a);
};

I made type trait for iterable is_iterable ; 我将类型特征is_iterable可迭代的is_iterable ; How to implement overload for operator= for iterable types? 如何为可迭代类型的operator=实现重载?

My approach: 我的方法:

template<typename TContainer, std::enable_if_t<is_iterable<TContainer>::value>>
A& operator=(const TContainer& val) {
// do stuff
}

but it doesn't work causing no viable overload error when i try to feed std::list or std::vector . 但是它不起作用,当我尝试喂std::liststd::vector时不会引起no viable overload错误。

So, how to fix it and is it possible to use that kind of overload? 那么,如何解决它,是否有可能使用这种重载?

When is_iterable<TContainer>::value is true, std::enable_if_t<is_iterable<TContainer>::value> is void , which is not a valid non-type template parameter. is_iterable<TContainer>::value为true时, std::enable_if_t<is_iterable<TContainer>::value>void ,这不是有效的非类型模板参数。 Define your container overload as 将您的容器重载定义为

template<typename TContainer,
         std::enable_if_t<is_iterable<TContainer>{}, int*> = nullptr>
A& operator=(const TContainer&)

Live demo 现场演示

Not sure if it is what you are looking for but I believe: 不确定是否是您要寻找的东西,但我相信:

template<typename TContainer>
A& operator=(const TContainer& container) {
    for (auto it = container.begin(); it != container.end(); it++) {
        // do stuff
    }
    return *this;
}

The template will be called only if other overloads does not match to type fed. 仅当其他重载与类型feed不匹配时,才调用模板。 If the type is not iterable, and error will occur on call to begin() and end() . 如果类型不可迭代,则调用begin()end()将发生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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