【问题标题】:Theoretically, would it be possible to allow multiple C++ templates to have the same name? [duplicate]从理论上讲,是否可以允许多个 C++ 模板具有相同的名称? [复制]
【发布时间】:2013-05-18 23:52:19
【问题描述】:

这就像函数重载。例如。可以这样做:

void foo(int i) {
  ;
}

// Function overload ftw.
void foo(int i, int j) {
  ;
}

但是(目前)还不行:

template<typename T>
class Foo {
};

// Fail!
template<typename T1, typename T2>
class Foo {
};

此功能不存在只是为了避免混淆吗?还是有什么理由这实际上没有意义?

【问题讨论】:

  • @CaptainObvlious 的优秀参考!

标签: c++


【解决方案1】:

不,在 c++ 中不可能做到这一点。

先查找模板,再查找导致无法知道哪个模板的参数。

它似乎与这个重复: Why is it not possible to overload class templates?

【讨论】:

  • 我知道这是不可能的。我的问题是为什么不呢?这个功能没有意义吗?或者它只是没有被指定出来?根据您(和 CaptainObvious)指出的另一个问题,这似乎只是一个从未被指定的问题。无论如何,谢谢你的回答!
【解决方案2】:

这不可能像你写的那样,但通过部分专业化很容易做到:

template <typename...> struct Foo;   // don't even define


template <typename T>
struct Foo<T>
{
    // ... "one-argument" version
};

template <typename T1, typename T2>
struct Foo<T1, T2>
{
    // ... "two-arguments" version
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2013-01-10
    • 2018-04-03
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多