0

考虑以下

#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: 错误: 'C::f' 声明为'inline' 变量
内联自动 C::f(value_type v) -> value_type {
test.cpp:11:26: error: 模板定义非模板'auto C::f'
test.cpp:11:26:错误:'value_type' 未在此范围内声明

问题出在value_type. 当我用它替换它时它会起作用,typename C<int, B>::value_type但这会更长,特别是在现实世界的应用程序中它可能会很长(我的情况)。有没有办法让这个工作与短变体一起工作?

PS:它适用于完整的模板专业化,但我必须只有部分专业化。

4

1 回答 1

2

当您使用模板时,您实际上是在定义一个新类型,即使是模板专业化也是如此。

因此,您的程序运行的正确方法是完全重新定义专业化。

#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;
}
于 2013-08-13T23:50:23.120 回答