问题
Trying to understand another question, I've simplified the example obtaining the following code.
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 compile it without problem; clang++ 3.5 give the following error
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)
^~~
Substituting one of the two auto
returning values with int
, there are no changes: g++ compile and clang++ give the error. Substituting both auto
with int
, the error disappear.
The template <typename T>
part is significant because the following code compile without problem with both compilers
template <bool>
struct foo
{
auto bar (int i)
{ return i; }
};
template <>
auto foo<true>::bar (int i)
{ return i; }
int main()
{
return 0;
}
My question is obvious: who's right?
g++ or clang++?
I suppose that g++ is right and that this is a bug from clang++ but I ask for confirmation.
p.s.: sorry for my bad English.
回答1:
I had the same issue, here is the solution.
Except you also should take into account that implicit auto return type is allowed only since C++14, so you should either use -std=c++14
compilation flag, or explicitly set the return type (for C++11).
The problem is that CLang does not match well specialization of the template functions of the template class. To overcome this you should have an empty declaration of the template class and separate specializations:
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;
}
来源:https://stackoverflow.com/questions/38061994/clang-auto-return-type-error-for-specialization-of-templated-method-in-templat