C++ 如何重载一个函数,该函数将不同模板对象的迭代器作为参数?

标签 c++ templates iterator c++14 overloading

我有两个相似的通用类 - MyClass1 和 MyClass2。 我希望函数“func”迭代 MyClass1 和/或 MyClass1 对象的元素。

但是我得到以下错误:

'auto' in return type deduced as 'Group3d<MyClass1<5> >' here but deduced as 'Group2d<MyClass1<5> >' in earlier return statement
        return funcForClass2<T>(start, end);
        ^

我不知道如何重载这个函数,因为类型是在调用它之后推导出来的。

有什么建议吗?

主要.cpp:

int main() {
    list<MyClass1<5>> a = {{0}, {-5}};
    auto res5 = func(a.begin(), a.end());

    list<MyClass2<6>> b = {{0, 3}, {0, -2}};
    auto res6 = func(b.begin(), b.end());
}

实用程序.h:

template<typename T>
using deref_iter_t = std::remove_reference_t<decltype(*std::declval<T>())>;

template<class Iterator>
auto func(Iterator start, Iterator end) {
    int dim;

    using T = deref_iter_t<Iterator>;

    dim = (start)->getDim();
    if (dim == 2) { // MyClass1 objects
        return funcForClass1<T>(start, end);
    }
    if (dim == 3) { // MyClass2 objects
        return funcForClass2<T>(start, end);
    }
}

最佳答案

假设 dim() 是 constexpr,您可以通过重载决议来完成。稍微简化示例以显示相关部分:

#include <utility>

struct A {
    static constexpr int x = 1;
};

struct B {
    static constexpr int x = 2;
};

int impl(std::integral_constant<int, 1> ) {
    return {};
}

char* impl(std::integral_constant<int, 2> ) {
    return {};
}


template<class T> auto foo(T t) {
    return impl(std::integral_constant<int, T::x>{});
}

int main() {
    auto f1 = foo(A{});
    auto f2 = foo(B{});
}

关于C++ 如何重载一个函数,该函数将不同模板对象的迭代器作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48344357/

相关文章:

iterator - 如何迭代结构集合作为特征对象引用的迭代器?

c++ - Win32 DLL 导入问题 (DllMain)

c++ - UTF-8、CString 和 CFile? (C++,MFC)

c++ - 用 constexpr 迭代

c++ - 无法获取已填充堆栈的顶部元素<char>

c++ - 有符号/无符号特征编程

php - 从 HTML 表单生成 HTML 文件

c++ - 如何在其他类的参数模板中使用某个类?

满足条件的元素的 Java 迭代器

c++ - 如何在没有其他变量的情况下获得当前位置?