gpt4 book ai didi

c++ - clang 自动返回模板类中模板方法特化的类型错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:46:08 24 4
gpt4 key购买 nike

试图理解another question ,我已经简化了获取以下代码的示例。

template <bool>
struct foo
{
template <typename T>
auto bar (int i)
{ return i; }
};

template <>
template <typename T>
auto foo<true>::bar (int i)
{ return i; }

int main()
{
return 0;
}

g++ 4.9.2编译没问题; clang++ 3.5 报如下错误

tmp_003-14,gcc,clang.cpp:12:20: error: out-of-line definition of 'bar' does not
match any declaration in 'foo<true>'
auto foo<true>::bar (int i)
^~~

用两个 auto 中的一个代替返回值 int ,没有变化:g++ 编译和 clang++ 给出错误。替换为 autoint , 错误消失。

template <typename T>这部分很重要,因为下面的代码在两个编译器上编译都没有问题

template <bool>
struct foo
{
auto bar (int i)
{ return i; }
};

template <>
auto foo<true>::bar (int i)
{ return i; }

int main()
{
return 0;
}

我的问题很明显:谁是对的?

g++ 还是 clang++?

我想 g++ 是正确的,这是 clang++ 的错误,但我要求确认。

p.s.:抱歉我的英语不好。

最佳答案

我有同样的问题,这里是 solution .除了你还应该考虑到隐式自动返回类型仅在 C++14 之后才被允许,所以你应该使用 -std=c++14 编译标志,或者显式设置返回类型(对于 C++11)。

问题是 CLang 不能很好地匹配模板类的模板函数的特化。为了克服这个问题,你应该有一个空的模板类声明和单独的特化:

template <bool>
struct foo;

template <>
struct foo <false>
{
template <typename T>
auto bar (int i)
{ return i; }
};


template <>
struct foo <true>
{
template <typename T>
auto bar (int i)
{ return i; }
};

int main()
{
return 0;
}

关于c++ - clang 自动返回模板类中模板方法特化的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38061994/

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