gpt4 book ai didi

C++ 类别名不编译为相同类型

转载 作者:太空狗 更新时间:2023-10-29 20:54:43 25 4
gpt4 key购买 nike

我不明白为什么下面的代码不能编译。我在使用 GCC 和 Clang 时遇到了同样的错误。有人可以解释或指出标准的一部分来解释为什么 p1p2 不是同一类型吗?

struct TypeT {};

struct TypeU {};

template<typename T, typename U = TypeU>
struct Foo {};


template<typename T, typename U>
struct Bar
{
};

template<typename T, template <typename> class U>
struct FooBar
{
};

template<typename T>
using FooAlias1 = Foo<T>;

template<typename T>
using FooAlias2 = Foo<T>;

template<typename T>
void DoStuff(const T& p1, const T& p2)
{
}

int main(void)
{
FooBar<TypeT, FooAlias1> p1;
FooBar<TypeT, FooAlias2> p2;
DoStuff(p1, p2);
}

这是 gcc 的输出:

$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

$ gcc -std=c++11 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:34:19: error: no matching function for call to ‘DoStuff(FooBar<TypeT, FooAlias1>&, FooBar<TypeT, FooAlias2>&)’
DoStuff(p1, p2);
^
test.cpp:34:19: note: candidate is:
test.cpp:26:6: note: template<class T> void DoStuff(const T&, const T&)
void DoStuff(const T& p1, const T& p2)
^
test.cpp:26:6: note: template argument deduction/substitution failed:
test.cpp:34:19: note: deduced conflicting types for parameter ‘const T’ (‘FooBar<TypeT, FooAlias1>’ and ‘FooBar<TypeT, FooAlias2>’)
DoStuff(p1, p2);

和 clang :

$ clang --version
Ubuntu clang version 3.4-1ubuntu3 (tags/RELEASE_34/final) (based on LLVM 3.4)

$ clang -std=c++11 test.cpp
test.cpp:34:5: error: no matching function for call to 'DoStuff'
DoStuff(p1, p2);
^~~~~~~
test.cpp:26:6: note: candidate template ignored: deduced conflicting types for parameter 'T' ('FooBar<[...], template FooAlias1>'
vs. 'FooBar<[...], template FooAlias2>')
void DoStuff(const T& p1, const T& p2)
^
1 error generated.

最佳答案

根据规范,§14.4,如果...,两种类型是等价的

— their corresponding template template-arguments refer to the same template.

但是您有两个不同的别名模板(§14.5.7)。它们不是类型别名。

  1. A template-declaration in which the declaration is an alias-declaration (Clause 7) declares the identifier to be a alias template. An alias template is a name for a family of types. The name of the alias template is a template-name.

关于C++ 类别名不编译为相同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com