具有两个或多个模板参数的c ++分配运算符

时间:2019-12-30 19:30:32

标签: c++ templates

代码示例:

#include <cstdio>

class Test
{
public:
    template<typename T, typename T2>
    bool operator =(T& value)
    {
        return true;
    }
};

template bool Test::operator= <int, bool>(int&);

int main()
{
    Test t;
    int gg = 1234;
    t = gg;
}

检查了几个编译器。 t = gg行的问题。 如果我删除第二个模板参数T2,则所有内容都会编译并运行。不允许有多个模板参数供赋值运算符使用吗?

4 个答案:

答案 0 :(得分:5)

您可以根据需要使用任意数量的模板参数。

问题在于,除了在运算符参数的声明中指定的模板参数或具有默认参数的模板参数外,编译器没有其他推断模板参数的方法。

因此您将必须编写类似以下内容的

#include <iostream>

class Test
{
public:
    template<typename T, typename T2>
    bool operator =( T& )
    {
        return true;
    }
};

template bool Test::operator= <int, bool>(int&);

int main()
{
    Test t;
    int gg = 1234;
    t.operator =<int, bool>(  gg );
}

答案 1 :(得分:2)

  

是否不允许有多个模板参数供赋值运算符使用? [原文]

不是不允许这样做,而是编译器无法推断出第二个参数。

如果您的函数看起来像这样:

template<typename T>
    bool operator =(T& value)

然后可以推导出模板参数T:它将是您尝试将t设置为的类型。由于这是所有模板参数,所以很好。

但是,当您有2个时会发生什么?

template<typename T, typename T2>
    bool operator =(T& value)

T很容易推论,但是T2又如何呢?编译器将如何知道T2应该是什么?答案是不可能的。

您可以通过直接调用operator函数来告诉它:

t.operator=<int, bool>(gg);

但是我想那不是你想要的。

不幸的是,以下表达式不起作用:

t =<bool> gg;

因此,我认为直接致电operator=()是您唯一的选择。


  

想象一下,在运算符中,我创建了T2类型的对象并将其放入一些列表。我没有显示完整的源代码,因为从这部分可以看到问题

这听起来像是您将operator=()用于并非旨在执行的操作。 operator=()实际上仅应用于复制另一个对象的状态。如果您需要设置状态的所有内容都不是T中固有的,那么您可能不应该为此目的使用operator=()

请考虑将其拆分为两个单独的功能,或将其全部移至非操作员功能。这样,将来其他人阅读您的代码后,您将更清楚自己在做什么。

答案 2 :(得分:1)

免责声明,我真的不明白您想要实现什么,并且我与其他人完全同意,您可能正在尝试使用赋值运算符来执行其不打算执行的操作。

但这是一段至少在语法上与您的要求接近的代码。您可以使Test成为类模板并使用普通的旧函数重载,而不必在运算符声明中指定两个参数。

template<typename T1, typename T2>
struct Test {

    T2 operator=(T1&) { return {}; }
    T1 operator=(T2&) { return {}; }
};

struct Foo {};

int main() {

    Test<int, Foo> t;

    int gg = 1234;
    Foo x = t = gg;  // <- this really looks weird, but works.

    Foo ff;
    int i = t = ff;

}

如果这不是您想要的,那么我们很可能需要有关您的复合用例的更多信息。

实时代码here

答案 3 :(得分:1)

听起来您实际上想要从第一个模板参数派生第二种类型。通常,这可以通过某种特征类型来实现:

#include <cstdio>

template < typename T >
struct TestTraits;

template <>
struct TestTraits< int >
{
    typedef bool T2;
};

class Test
{
public:
    template<typename T>
    bool operator =(T& value)
    {
        using T2 = typename TestTraits< T >::T2;
        return true;
    }
};

int main()
{
    Test t;
    int gg = 1234;
    t = gg;
}