【问题标题】:C++ working with templates for integral types, candidate template is ignoredC++ 使用整数类型的模板,候选模板被忽略
【发布时间】:2019-02-19 11:31:45
【问题描述】:

我有一个带有重载operator + 的类以供添加。我希望用它来添加一个整数类型及其整数成员之一。但是,候选模板被忽略了。这样做的正确方法是什么?

#include <iostream>

using namespace std;

    template <class T>
    class A
    {
    public:
        A(uint32_t a = 0)
        : _a(a)
        { }

        template <class TT, typename std::enable_if<std::is_integral<TT>::value>::type>
        TT operator + (TT right) { return _a + right; }

    private:
        uint32_t _a;
    };

    class AT : public A<AT>
    {
    public:
        AT() : A(10) { }
    };
int main()
{
    AT at;
    cout<< (at + 10);

    return 0;
}

【问题讨论】:

标签: c++ templates operator-overloading overloading


【解决方案1】:

第二个模板参数typename std::enable_if&lt;std::is_integral&lt;TT&gt;::value&gt;::type声明了一个匿名模板参数,在at + 10的调用中不能推导出来。

我想你想要的可能是

// specify default value for the 2nd template parameter
template <class TT, typename std::enable_if<std::is_integral<TT>::value>::type* = nullptr>
T operator + (TT right) { return _a + right; }

LIVE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多