考虑以下
#include <iostream>
template <typename T, bool B>
struct C {
using value_type = T;
value_type f(value_type v);
};
template <bool B>
auto C<int, B>::f(value_type v) -> value_type {
return v;
}
int main(int argc, char * argv[]) {
C<int, true> c;
std::cout << c.f(5) << std::endl;
return 0;
}
使用 g++ 4.9 我得到错误
test.cpp:11:26: error: 'C::f' declared as an 'inline' variable
inline auto C::f(value_type v) -> value_type {
test.cpp:11:26: error: template definition of non-template 'auto C::f'
test.cpp:11:26: error: 'value_type' was not declared in this scope
问题出在 value_type
.当我用 typename C<int, B>::value_type
替换它时它会起作用但这要长得多,特别是在现实世界的应用程序中,它可能会很长(我的情况)。有没有办法使它与短变体一起工作?
PS:它适用于完整的模板特化,但我只需要部分特化。
最佳答案
当您使用模板时,实际上您是在定义一种新类型,即使是针对模板特化也是如此。
因此,让您的程序正常运行的正确方法是完全重新定义特化。
#include <iostream>
template <typename T, bool B>
struct C {
T f(T v);
};
template <bool B>
struct C<int,B> {
int f(int v) {
return v;
}
};
int main(int argc, char * argv[]) {
C<int, true> c;
std::cout << c.f(5) << std::endl;
return 0;
}
关于c++ - 模板偏特化和从属名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18221015/